home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1999 January / EnigmA AMIGA RUN 33 (1999)(G.R. Edizioni)(IT)[!][issue 1999-01].iso / earcd / faq / computer-lang / java / programmers-faq.z / programmers-faq
Internet Message Format  |  1999-01-01  |  181KB

  1. From: pvdl@best.com(Peter van der Linden)
  2. Newsgroups: comp.lang.java.programmer,comp.lang.java.help,comp.lang.java.gui,comp.answers,news.answers
  3. Subject: Java Programmers FAQ
  4. Followup-To: poster
  5. Date: 17 Nov 1997 09:20:27 -0800
  6. Lines: 3673
  7. Approved: news-answers-request@MIT.EDU
  8. Message-ID: <64pucr$t48$1@shell15.ba.best.com>
  9. NNTP-Posting-Host: shell15.ba.best.com
  10. X-Trace: 879787229 7287 pvdl  206.184.139.132
  11. Summary: This posting answers frequently-asked questions by Java programmers
  12. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!tribune.meitca.com!ulowell.uml.edu!newsfeed.wizvax.net!usenet.logical.net!nntprelay.mathworks.com!news1.best.com!nntp1.ba.best.com!not-for-mail
  13. Xref: senator-bedfellow.mit.edu comp.lang.java.programmer:96540 comp.lang.java.help:9606 comp.lang.java.gui:5433 comp.answers:28982 news.answers:116970
  14.  
  15. Archive-name: computer-lang/java/programmers-faq
  16. Posting-Frequency: twice-weekly
  17. Last-modified: 1997/11/17
  18. URL: http://www.best.com/~pvdl/javafaq.html
  19. Copyright: (c) 1997 Peter van der Linden
  20. Maintainer: Peter van der Linden (pvdl@best.com)
  21.  
  22. ------------------------------------------------------------------------
  23.  
  24. Help stop Microsoft from trying to destroy Java Portability
  25.  
  26. As the Java Programmers FAQ maintainer, I ask you to drop all use of the
  27. near-Java tools from Microsoft. Don't use any Microsoft near-Java tools
  28. until Microsoft stops trying to undermine and divide Java.
  29.  
  30.    * don't use J++ or Visual J++ (use the tools from a score of other
  31.      vendors)
  32.    * don't use Internet Explorer (use Netscape)
  33.    * don't use the Microsoft Java SDK. (Use Sun's JDK)
  34.  
  35. The biggest value of Java is its portability. If programmers accept
  36. Microsoft tools that destroy Java portability by changing core Java
  37. libraries and protocols, it will set the computer industry back years.
  38.  
  39. Support 100% Pure Java. Encourage Microsoft to make its near-Java
  40. implementation pass the Java compatability test suite. Junk all non-standard
  41. Microsoft not-quite-Java software. Use the free Java compilers downloadable
  42. from http://java.sun.com.
  43.  
  44. ------------------------------------------------------------------------
  45.  
  46. Frequently Asked Questions (with answers) for Java programmers
  47.  
  48. Most of the Java FAQs here are intended for experienced programmers. To
  49. distinguish this from other Java FAQs, this is the "Programmer's FAQ" and
  50. will be posted mostly in
  51.  
  52.    * comp.lang.java.programmer
  53.    * comp.lang.java.help
  54.    * comp.lang.java.gui
  55.    * comp.answers.
  56.  
  57. Latest copy of this FAQ is available at: http://www.best.com/~pvdl
  58.  
  59. This FAQ reflects the latest and most current version of Java: JDK 1.1.4.
  60.  
  61. 0. A WORD FROM OUR SPONSOR
  62. 1. LOOKING FOR INFORMATION
  63. 2. COMPILERS, ETC.
  64. 3. LANGUAGE ISSUES
  65. 4. AWT and Related Topics
  66.  
  67.      4.0 AWT
  68.      4.1 APPLETS
  69.      4.2 BROWSERS
  70.  
  71. 5. CORE LIBRARIES
  72. 6. I/O
  73. 7. NETWORKING & DISTRIBUTED OBJECTS
  74. 8. MULTI-MEDIA
  75. 9. SECURITY
  76. 10. Java IDIOMS
  77. 11. FOR C and C++ AFFICIONADOS
  78. 12. FURTHER RESOURCES
  79.  
  80. -------------------------------------------------------------------------
  81.  
  82. 0. A WORD FROM OUR SPONSOR
  83.  
  84. This Java FAQ is compiled and maintained as a service to the Java community.
  85.  
  86. Learning Java
  87.  
  88. Please consider these books when you are looking for a programming text. You
  89. can get more info on these books at http://www.best.com/~pvdl
  90.  
  91.      0.1"Not Just Java" by Peter van der Linden, $35
  92.      publ 1997 Sun Press/Prentice-Hall, ISBN 0-13-864638-4
  93.  
  94.      This should be your first book on Java -- and it doesn't teach Java
  95.      programming. Instead, this book describes the trends and implications
  96.      of Java and related technologies. Clear explanations with diagrams
  97.      covering Java, CORBA, thin clients, network computers, RMI, multi-tier
  98.      systems, Java threads, ActiveX, OLE, JavaBeans, JDBC, etc. For
  99.      engineers, executives, and all the job titles in between.
  100.  
  101.      Look at reader reviews at:
  102.      http://www.amazon.com/exec/obidos/ISBN=0138646384/4112-4025659-560808
  103.  
  104.      0.2 "Just Java Third Ed." by Peter van der Linden, $44.95
  105.      publ Oct 1997 Sun Press/Prentice-Hall, ISBN 0-13-784174-4
  106.  
  107.      An introduction to Java Programming, for people who can already program
  108.      in another language. Filled with common sense examples, and anecdotes
  109.      from the computer industry. Learning Java is enjoyable, stimulating fun
  110.      with this book. Comes with a CD including the compiler and sample code.
  111.      Covers Java 1.0 and 1.1, with a preview of Java 1.2 Swing classes.
  112.  
  113.      Look at reviews at:
  114.      http://www.amazon.com/exec/obidos/ISBN=0137841744/7892-5006833-225957
  115.  
  116.      0.3 "Expert C Programming" by Peter van der Linden, $35,
  117.      publ 1994 Sun Press/Prentice-Hall, ISBN 0-13-177429-8.
  118.  
  119.      Everyone's second book on C. Unix Review gave it "5 stars". "Expert C
  120.      Programming" teaches you the tips and techniques used by the very best
  121.      C programmers in the world. Based on a decade in Sun's compiler and OS
  122.      groups.
  123.  
  124.      Please look at reader reviews at:
  125.      http://www.amazon.com/exec/obidos/ISBN=0131774298/4112-4025659-560808
  126.  
  127.      These books can be ordered online from http://www.cbooks.com Or by
  128.      phone from Quantum Books 617 494-5042 (in USA) during business hours.
  129.  
  130.                              -------------------
  131.  
  132. 1. Looking For Information
  133.  
  134.      1.0 Is Java "Open" or Proprietary?
  135.           A.  Java is a freely-available open specification.  Sun
  136.           Microsystems publishes the Java specifications and public
  137.           interfaces as open specifications that can be independently
  138.           implemented by anyone without charge (termed a "clean-room"
  139.           implementation in industry jargon).  Specifically, Sun includes a
  140.           royalty-free license in the front of the Addison-Wesley books
  141.           containing the specification.
  142.  
  143.           Further, by submitting Java specifications to be ISO/IEC
  144.           standards, Sun is giving up some control in exchange for the world
  145.           being able to refer to a Java specification that is guaranteed to
  146.           be open by ISO/IEC's charter and rules.
  147.  
  148.           Sun Microsystems has invested significant time and money to create
  149.           a Java implementation. It has licensed, for a fee, the results of
  150.           this work (the source code for the implementation) to 117
  151.           companies and organizations who have asked for it, including
  152.           competitor Microsoft.  Sun has also allowed free download and use
  153.           of the Java implementation (binary executables) by anyone.  Over 1
  154.           million computer users have downloaded the JDK binaries for free
  155.           in the seven month period from February 1997.
  156.  
  157.      1.1 What is the best way to refer someone to the FAQ when they ask
  158.      question I know is answered there?
  159.  
  160.           A. The Java Programmers FAQ gives the answer to your question in
  161.           section N.n. ...
  162.  
  163.           This gives them the answer, and shows them where to go for future
  164.           questions (it also demonstrates that the FAQ can answer their
  165.           questions, providing an incentive to go there next time.)
  166.  
  167.      1.2 Where can I look at the definitive Java Language Specification?
  168.  
  169.           A. This is available online at:
  170.                http://java.sun.com/docs/books/jls/html/index.html (Java 1.0)
  171.           and the Java 1.1 update at:
  172.                http://java.sun.com/docs/books/jls/html/1.1Update.html
  173.           This is also available as a book in printed form (details at
  174.           website).
  175.      1.3 Where can I find a full list of Java books and book reviews?
  176.           A. http://lightyear.ncsa.uiuc.edu/~srp/java/reviews.html
  177.      1.4 How do I search Deja News for past postings on Java topics, e.g.
  178.      the FAQ?
  179.           A. Go to http://www.dejanews.com/home_sf.shtml
  180.              + Under "Newsgroups" enter "comp.lang.java.programmer" (or
  181.                whatever)
  182.              + Under "Subject" enter "Frotteur" (or other topic you find
  183.                pressing)
  184.              + Click "Create Filter"
  185.              + It will go to a new document, and you should click the link
  186.                labeled
  187.  
  188.                nnn Documents (nnn is some number).
  189.           This makes finding information very easy.
  190.  
  191.           Also look at http://sunsite.unc.edu/java/cgi-bin/query
  192.           and look at http://asknpac.npac.syr.edu/ for Java newsgroup search
  193.  
  194.           http://www.javaworld.com/search.html can search the Javaworld
  195.           newspaper
  196.  
  197.      1.5 How do I check on known bugs in JDK 1.1?
  198.           A. Look at
  199.           http://java.sun.com/products/jdk/1.1/knownbugs/index.html
  200.  
  201.           Note that only bugs that Sun deems "important" are listed there.
  202.           The criteria for "important" are not published.
  203.  
  204.           After you have checked whether the bug is already listed, you can
  205.           submit a bug report through:
  206.           http://java.sun.com:80/cgi-bin/bugreport.cgi
  207.  
  208.           You can even send in an RFE or ease-of-use issue there!
  209.  
  210.           If you go to the JDC (that's the Java Developer's Connection) you
  211.           can do a keyword search against the internal Javasoft bugtraq
  212.           database, looking by keyword or bug number. JDC has free
  213.           registration.
  214.                http://developer.javasoft.com should do it.
  215.  
  216.                Also, there's a longer list of known bugs at:
  217.  
  218.                http://www2.vo.lu/homepages/gmid/java.htm
  219.      1.6 Is there a Java port to Windows 3.1?
  220.           A. Yes, several. IBM's ADK1.02 is available at the following
  221.           locations:
  222.                http://ncc.hursley.ibm.com/javainfo/latest/answers/faq0.html
  223.                http://www.alphaworks.ibm.com/formula
  224.           Netscape Navigator for Win3.1 has Java support [anyone know the
  225.           version?]
  226.  
  227.           You could also consider JavaSoft's JavaPC $100 kit that converts a
  228.           PC into a thin client Java system. Details are sparse as yet, but
  229.           this is probably more for business users than personal PCs.
  230.  
  231.           Check http://java.sun.com/pr/1997/april/pr970402-07.html
  232.      1.7 I see a lot of postings from magazines soliciting Java articles.
  233.      Are these legitimate?
  234.           A. Anyone considering writing for the "Java Developer's Journal",
  235.           or any other Sys-Con publication, should be aware that there have
  236.           been several instances of programmers complaining that JDJ has not
  237.           paid them for commissioned articles.
  238.  
  239.           Another programmer reported that he was not paid by Sys-Con for an
  240.           article for their Delphi magazine. There is a pattern of
  241.           programmers complaining that SYS-CON has not paid them.
  242.  
  243.           The issue is that Sys-Con will only pay for articles that it
  244.           actually prints, even when it explicitly commissioned the article
  245.           from you. Some other publishers pay a cancellation or "kill" fee
  246.           when they don't run a work they have commissioned. Programmer
  247.           beware, and please don't support magazines that are in conflict
  248.           over payment with their programmer contributors.
  249.      1.8 What are the good folks at project Gnu doing with Java?
  250.           A. Guava (the Gnu Java compiler) can be found at
  251.                http://http.cs.berkeley.edu/~engberg/guavac/
  252.           Kaffe (a JVM) can be found at
  253.                http://www.kaffe.org
  254.      1.9 Where can I find information about Java Certification?
  255.           A. Sun is sponsoring an examination which programmers worldwide
  256.           can take. Those passing can use the designation "Sun certified
  257.           Java Programmer". There is also a second level test, involving
  258.           writing a program to spec, and taking a further test. That results
  259.           in the qualification "Sun Certified Java Developer". You can find
  260.           out all about the exam at:
  261.                http://www.sun.com/service/suned/cert/scjp_11.html
  262.                and
  263.                http://www.sun.com/service/suned/cert/scjd_11.html
  264.           It costs $150 to sit the Java Programmer exam. It is not trivial
  265.           to pass the Java certification exam. It requires understanding the
  266.           objectives of the test, and the material that is tested for. These
  267.           are given, along with sample questions, at the URL mentioned
  268.           above.
  269.      1.10 I'm looking for a Java style guide on naming conventions.
  270.           A. Check out the section "Naming Conventions" in the language
  271.           pecification
  272.                http://java.sun.com/docs/books/jls/html/6.doc.html#11186
  273.           Also take a look at Doug Lea's draft coding standard -
  274.                http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
  275.      1.11  Where can I find information about future Java APIs?
  276.           A.  JavaSoft has followed a policy of creating new APIs in
  277.           consultation with leading industry participants, then posting the
  278.           draft specification for public review and comments.  Check the
  279.           JavaSoft roadmap of new APIs and products at
  280.           http://Java.sun.com:80/products/api-overview/index.html
  281.           Also, some APIs that are under consideration, possibly for JDK 1.2
  282.           are at:
  283.                http://java.sun.com/products/jdk/preview/docs/
  284.      1.12 How can I find links to recent news about Java?
  285.           A. http://lightyear.ncsa.uiuc.edu/~srp/java/javanews.html This
  286.           site contains links to late-breaking online news stories about
  287.           Java. Highly recommended. Also http://www.roaster.com/news/ is a
  288.           good Java news source.
  289.  
  290.           This site is a source of independent news and commentary on the
  291.           computer industry, including Java.
  292.           http://www.pjprimer.com/media.html. (You have to subscribe
  293.           ($10/year, 30 day free trial).
  294.      1.13 What computers have Java ports?
  295.           A. A list of JDK ports is available from
  296.                http://java.sun.com/cgi-bin/java-ports.cgi
  297.  
  298.  
  299.  
  300.                              -------------------
  301.  
  302. 2. COMPILERS, ETC.
  303.  
  304.      2.1 Why did I get an OutOfMemory error when porting working code from
  305.      jdk 1.02 -> 1.1
  306.           A. The preset memory limit has changed. It went down to 16Mb so as
  307.           not to penalize low memory machines. You can adjust it with
  308.                java -mx32m Frotz
  309.           to get a 32Mb extent.
  310.  
  311.           Also see the Runtime methods freeMemory() and totalMemory().
  312.      2.2 Why do I get a "Statement not reached" error from javac for no
  313.      apparent reason?
  314.           A. JDK1.0 has a limit of 63 words of storage for local variables
  315.           in any method. longs and doubles require two words of storage, and
  316.           all other primitive types and all reference types require one
  317.           word. If you assign values to more than 63 words of local
  318.           variables, you will get a "Statement not reached" error on the
  319.           statement after you assign to the variable that contains the 64th
  320.           word. In JDK 1.1, the low limit was removed.
  321.      2.3 Is there a lex and yacc or preferably a flex and bison equivalent
  322.      for Java?
  323.           A. There is a lex equivalent called JavaLex and a yacc equivalent
  324.           called CUP.
  325.  
  326.           LALR(1) parser
  327.                JavaLex and JavaCup:
  328.                http://www.cs.princeton.edu/~appel/modern/java/
  329.           LL(k) parser
  330.                JavaCC: http://www.suntest.com/Jack/
  331.      2.4 Where can I find a byte code obfuscator?
  332.           A. HashJava: http://www.blackdown.org/~kbs/hashjava.html
  333.           http://www.primenet.com/~ej/
  334.           http://www.math.gatech.edu/~mladue/HoseMocha.java
  335.           There are also commercial products, such as SourceAgain from
  336.           http://www.ahpah.com
  337.  
  338.           Some people have reported problems using these with JDK 1.1.
  339.  
  340.           This obfuscator has been updated to be fully compatible with JDK
  341.           1.0 and 1.1:
  342.  
  343.           http://www.monmouth.com/~neil/Obfuscate.html
  344.      2.5 Which program is used to create .zip files, compatible with the
  345.      java* programs? (eg classes.zip, moz3_0.zip)
  346.           A. Use the jar-tool from JDK1.1(.1):
  347.                jar [ options ] [manifest] destination input-file
  348.                [input-files]
  349.           E.g.:
  350.                jar cvf myJarFile.jar *.class
  351.           creates a compressed archive
  352.                jar cvfO myJarFile.zip *.class
  353.           creates it fullsize (uncompressed) (note the 'O'-option used for
  354.           JDK1.0.2)
  355.  
  356.           On Unix you can also use:
  357.                zip -rn ".class" my_file.zip *
  358.           Info-ZIP home page: http://www.cdrom.com/pub/infozip/
  359.           Latest source code:
  360.           ftp://ftp.uu.net/pub/archiving/zip/src/zip21.zip
  361.  
  362.           Netscape's command line version of its JAR packager and signing
  363.           tool is called "zigbert". They also have a signing tool with GUI
  364.           written in Java. More info at:
  365.                http://developer.netscape.com/software/signedobj/jarpack.html
  366.           If you zip your .class files for JDK 1.0.2 (for 1.1 you'll use a
  367.           Jar)
  368.                1. zip your files uncompressed (can use WinZip 6.2 up);
  369.                     Unix command: zip -r0 classes.zip <directories>
  370.                2. Make sure the main class has no directory beside it inside
  371.                the archive, but your packages do;
  372.  
  373.                3. Put the archive in the same directory as the .html page;
  374.  
  375.                4. Put something like the following tag in the .html file:
  376.                     <APPLET CODEBASE="."
  377.                     ARCHIVE=my_zip_file.zip,myOtherZip.zip,thirdfile.zip
  378.                     CODE="my_main_class.class"
  379.                     WIDTH=600 HEIGHT=250>
  380.                     </APPLET>
  381.           From JDK 1.1 on, an example of the applet tag used with a jar file
  382.           is
  383.                <APPLET ARCHIVE=myfile.jar
  384.                CODE=myapplet.class
  385.                WIDTH=600 HEIGHT=250>
  386.                </APPLET>
  387.           These lines will use an applet called myapplet that can be found
  388.           in the jarfile myfile.jar. You can supply several jar filenames in
  389.           a comma-separated list. Jar files are in compressed PKZIP format.
  390.      2.6 Can I compile a Java .class file to a binary executable, .exe on a
  391.      PC?
  392.           A. Some companies make products that do this, but it takes away
  393.           one of the most significant benefits of Java: portability of
  394.           executables. Consider carefully why you want to do this, and
  395.           whether there is a Java way to accomplish your goal. There may be
  396.           a good reason for compiling to native code, but it needs to be
  397.           thought through.
  398.      2.7 How can I performance profile my Java code?
  399.           A. java -prof MyClass
  400.  
  401.           produces some basic output in a file called java.prof, showing the
  402.  
  403.           number of times methods were invoked. The output lines are of the
  404.           form:
  405.  
  406.  
  407.               # of calls     method called      called by        time spent
  408.           On a Unix system, you can sort the file with something like
  409.                sort -r +82 <java.prof > java.sort
  410.           More and better Java tools are a third party opportunity.
  411.      2.8 When I use javadoc and I click on any java class included in the
  412.      jdk why do I get this message?
  413.      Netscape is unable to find the file or directory named:
  414.           /E|/Jwrkshop/JDK/bin/java.lang.Throwable.html
  415.  
  416.           A. References to the JDK classes assume that *all* generated html
  417.           files are in the same directory and, in fact, that all files for
  418.           all classes referenced are generated at the same time. There is no
  419.           way to generate files incrementally and have them all reference
  420.           each other, as you would like.
  421.  
  422.           As long as you have source for everything involved (including the
  423.           JDK and all third-party classes), you can list all of your
  424.           packages and all of the others on the javadoc command line and
  425.           generate the whole set at once, but it is a real pain. Of course,
  426.           if you receive any libraries as .class files, even this workaround
  427.           will not suffice.
  428.  
  429.           Also javadoc will not generate the image files - you need to get
  430.           them from the images directory under the JDK API documentation
  431.           files. You can just copy the entire directory into your own doc
  432.           directory. javadoc is a very nice concept, with a few
  433.           implementation flaws.
  434.      2.9 I'm working on a project with lots of classes and I use the JDK. A
  435.      recompile from scratch takes forever when I do it a class at a time.
  436.      How do I recompile everything?
  437.           A. The first way is
  438.                javac *.java
  439.           Another way is
  440.                javac -depend tip.java
  441.           where "tip.java" is a class "at the tip of the iceberg", i.e. that
  442.           depends on (uses) all the other classes. Typically, this may be
  443.           your main class. However, "-depend" is known to be buggy and
  444.           cannot be relied upon. It also doesn't issue compile commands in
  445.           parallel to make use of multi-processor systems.
  446.  
  447.           Without the "-depend" option, the standard "javac files" doesn't
  448.           look beyond the immediately adjacent dependencies to find classes
  449.           lower down the hierarchy where the source has changed.
  450.  
  451.           The -depend options searches recursively for depending classes and
  452.           recompiles it. This option doesn't help when you have dynamically
  453.           loaded classes whose names cannot be determined by thecompiler
  454.           from the dependency graph. E.g. you use something like
  455.  
  456.                Class.forName(argv[0]);
  457.  
  458.           The author of the code using those classes should make sure that
  459.           those classes are mentioned in a Makefile.
  460.      2.10 Why do I get the java.lang.UnsatisfiedLinkError when I run my Java
  461.      program containing Native Method invocations?
  462.           A. Your program is not able to find your shared library or DLL.
  463.  
  464.           On Windows 95/NT, make sure that the DLL exists in a path that is
  465.           included within the PATH environment variable.
  466.  
  467.           On Solaris, make sure that the environment variable
  468.           LD_LIBRARY_PATH includes the path of your shared library.
  469.  
  470.                              -------------------
  471.  
  472. 3. LANGUAGE ISSUES
  473.  
  474.      3.1 Why doesn't my "hello world" program work?
  475.           A. Common causes of failure are:
  476.              + First, did you write an applet or an application? If an
  477.                applet, you must make sure that you did extend the
  478.                java.applet.Applet class. You must declare your class that is
  479.                extended from Applet as "public". If you don't, unfortunately
  480.                some browsers will still run the code, while others won't.
  481.              + Your class name and the file name must match exactly, even
  482.                letter case. If your class is HelloWorld, your source file
  483.                must be HelloWorld.java
  484.              + In JDK 1.0.2 the $CLASSPATH environment variable should
  485.                include "." the current dir.
  486.           In JDK 1.1, users are no longer required to set the CLASSPATH.
  487.  
  488.           From JDK 1.1.2 on, it is generally an ERROR if the user sets the
  489.           CLASSPATH! (except that use of rmic apparently still requires it).
  490.      3.2 How can I program linked lists if Java doesn't have pointers?
  491.           A. Of all the misconceptions about Java, this is the most
  492.           egregious. Far from not having pointers, in Java, object-oriented
  493.           programming is conducted exclusively with pointers. In other
  494.           words, objects are only ever accessed through pointers, never
  495.           directly. The pointers are termed "references" and they are
  496.           automatically dereferenced for you.
  497.  
  498.           Java does not have pointer arithmetic or untyped casting. By
  499.           removing the ability for programmers to create and modify pointers
  500.           in arbitrary ways, Java makes memorymanagement more reliable,
  501.           while still allowing dynamic data structures. Also note that Java
  502.           has NullPointerException, not NullReferenceException.
  503.  
  504.           A linked list class in Java might start like this:
  505.  
  506.                public class linkedlist {
  507.                public linkedlist head;
  508.                public linkedlist next;
  509.                public Object data;
  510.                public linkedlist advanceToNext(linkedlist current) { ...
  511.                ... }
  512.  
  513.           Another choice for a linked list structure is to use the built-in
  514.           class java.util.Vector which accepts and stores arbitrary amounts
  515.           of Object data (as a linked list does), and retrieves it by index
  516.           number on demand (as an array does). It grows automatically as
  517.           needed to accommodate more elements. Insertion at the front of a
  518.           Vector is a slow operation compared with insertion in a linked
  519.           list, but retrieval is fast. Which is more important in the
  520.           application you have?
  521.      3.3 What is the true story about how parameters are passed in Java? Is
  522.      is by value or by reference?
  523.           A. All parameters (values of primitive types, & values that are
  524.           references to objects) are passed by value [JLS sect 8.4.1].
  525.           However this does not tell the whole story, as objects are always
  526.           manipulated through reference variables in Java. Thus one can
  527.           equally say that Objects are passed by reference (and the
  528.           reference variable is passed by value). This is a consequence of
  529.           the fact that variables do not take on the values of "objects" but
  530.           values of "references to objects" as described in the previous
  531.           answer.
  532.  
  533.           Bottom line: primitive type arguments (int, char, etc) _do not_
  534.           change when the corresponding parameter is changed. The fields of
  535.           object type arguments _do_ change when the corresponding parameter
  536.           fields are changed.
  537.      3.4 How, then, can I pass an object to a method, and have the method
  538.      change the reference so it points to a different object back in the
  539.      calling code?
  540.           A. There are two ways. The obvious way is "just add another level
  541.           of indirection" -- wrap the object in another class, whose purpose
  542.           is simply to be passed as a parameter, allowing the nested object
  543.           reference to be modified.
  544.  
  545.           The second alternative is a clearer variant of this. Pass in a
  546.           single element array. Since arrays are objects, this works.
  547.  
  548.                void jfoo(Object ref[]){
  549.                    ref[0] = new Object();
  550.                }
  551.  
  552.                ...
  553.  
  554.                Object kludge[] = new Object[1];
  555.                kludge[0]= myObj;
  556.                jfoo(kludge);
  557.                if (kludge[0] == myObj) ...
  558.                else ...
  559.  
  560.      3.5 Why is String a final class? I often want to override it in some
  561.      way.
  562.           A. There are several reasons.
  563.  
  564.           The simplest is that being final guarantees that instances of
  565.           String are immutable. (The String class implements immutable
  566.           objects, but if it were not final it would be possible to write a
  567.           subclass of String which permitted instances to be changed.) But
  568.           that's an unsatisfying answer,
  569.           because the real question is "Why must Strings be immutable?"
  570.  
  571.           One reason is efficiency. It's easier to optimize accesses to an
  572.           object that is known to be immutable. Strings are very commonly
  573.           used, even used behind the scenes by the Java compiler. Efficiency
  574.           gains in the String class can yield big dividends. If no one can
  575.           change a String, then
  576.           you never have to worry about who else has a reference to your
  577.           String.
  578.  
  579.           A more compelling reason is security. Before String was changed to
  580.           be final (while Java 1.0 was still in beta) there was a race
  581.           condition which could be used to subvert security restrictions. It
  582.           had to do with having one thread change a pathname while another
  583.           thread was about to open it.
  584.  
  585.           There are other ways to solve these problems, but making String
  586.           final is the one that the designers chose.
  587.      3.6 What happened to "private protected"?
  588.           A. It first appeared in JDK 1.0 FCS (it had not been in the
  589.           Betas). Then it was removed in JDK 1.1. It was an ugly hack
  590.           syntax-wise, and it didn't fit consistently with the other access
  591.           modifiers. It never worked properly: in the versions of the JDK
  592.           before it was removed, calls to private protected methods were not
  593.           dynamically bound, as they should have been. It added very little
  594.           capability to the language. It's always a bad idea to reuse
  595.           existing keywords with a different meaning. Using two of them
  596.           together only compounds the sin.
  597.  
  598.           The official story is that it was a bug. That's not the full
  599.           story. Private protected was put in because it was championed by a
  600.           strong advocate. It was pulled out when he was overruled by
  601.           popular acclamation.
  602.      3.7 I extended the class called Frotz, and the compiler is giving me an
  603.      error message "No constructor Frotz()" in the child class. Why?
  604.           A. When you define a constructor for a class, unless you
  605.           explicitly call the superclass' constructor at the start, a call
  606.           to the superclass' parameterless constructor is implicitly
  607.           inserted. The problem you're seeing is what happens when the
  608.           superclass doesn't *have* a parameterless constructor. The
  609.           solution is usually to call the correct version of the superclass'
  610.           constructor with the right parameters.
  611.      3.8 Why does <unexpected> happen in Java floating point?
  612.           A. There are several unexpected things that seem to bite
  613.           programmers with floating point. Invariably this is a result of
  614.           the programmer not being fully conversant with FP, rather than
  615.           some fault in Java.
  616.  
  617.           If you seem to be having problems with floating point, your
  618.           problem probably stems from the fact that floating-point
  619.           arithmetic is inherently imprecise. You can expect up to 7 digits
  620.           of precision with floats and 16 digits with doubles. However, that
  621.           does not mean that a number that can be exactly represented in 7
  622.           digits decimal, can be exactly represented as a binary floating
  623.           point number. On the contrary, that is usually not the case.
  624.  
  625.           Additionally, when Java converts floating point numbers to a
  626.           String, as is done when they are output, enough digits are printed
  627.           so the number can be read back in with no loss of precision. For
  628.           this reason, you may see more "inaccuracies" in floating point
  629.           output than you are used to. This policy actually gives you more
  630.           consistent results than on a system where floating point output is
  631.           deliberately rounded to make the output "pretty".
  632.  
  633.           There is a limitation of FP in JDK 1.0 (fixed in JDK 1.1). Namely,
  634.           when you output a floating point number in Java 1.0, the result is
  635.           system-dependent and contains no more than six digits after the
  636.           decimal point. This bug is fixed in Java 1.1.
  637.  
  638.           For more information and detailed specifications on how Java deals
  639.           with floating point, see the following URLs:
  640.      http://java.sun.com/products/jdk/1.1/compatibility.html#incompatibilities
  641.  
  642.      http://java.sun.com/doc/language_specification/javalang.doc.html#1466
  643.      http://java.sun.com/doc/language_specification/javalang.doc.html#5899
  644.  
  645.  
  646.           If you want the rounded floating point output that most languages
  647.           have, use the new java.text package of Java 1.1 to limit the
  648.           number of digits that are output. If you need more precision than
  649.           about 16 digits, use the BigInteger and BigDecimal classes of Java
  650.           1.1.
  651.      3.9 Why do I get the compiler error message
  652.           urltest.java:8: Variable test may not have been initialized.
  653.  
  654.                URL test;
  655.                try { test = new URL("http://osprey.avs.dec.com");
  656.                } catch (MalformedURLException e) {}
  657.                System.out.println("this is url " + test);
  658.                }
  659.  
  660.           A. If an exception is raised in the try clause, test will not be
  661.           given a value, yet you are using it in the catch clause. The
  662.           solution is either to declare test with an explicit initial value
  663.           of null, or (better) to print out the e.getMessage() string of the
  664.           exception.
  665.      3.10 Why do I get this compiler error message?
  666.  
  667.           public static void main(String[] args) {
  668.           ^
  669.           Statement expected.
  670.           public static final float Conversion_Factor = 39.37;
  671.           ^
  672.           Type expected.
  673.  
  674.           A. A. Argument declarations and variable declarations inside
  675.           methods are never given the "public", or "static" keywords. They
  676.           are not public or static because they are local to a method. (They
  677.           used not to be allowed the "final" keyword either, but there was
  678.           not good reason for that restriction and it was dropped in JDK
  679.           1.1). Move your public or static declarations outside the method.
  680.           They are usually put at the beginning of the class.
  681.      3.11 Why do I get this compiler error message?
  682.  
  683.           MyApplet.java:11: No constructor matching MyCheckbox(myApplet)
  684.           found in class MyCheckbox.
  685.  
  686.           bp1 = new MyCheckbox(this);
  687.           ^
  688.           1 error
  689.  
  690.           A. The first thing to check is whether you gave a return value to
  691.           the constructor, like this:
  692.  
  693.                public void MyCheckbox( Container parent )
  694.  
  695.           If you did, the compiler will think it is an ordinary method, not
  696.           a constructor. This is a very common mistake, and quite hard to
  697.           spot.
  698.      3.12 Why do I get the compiler error message
  699.  
  700. T.java:96: Can't access protected method clone in class java.lang.Object.
  701. OtherT is not a subclass of the current class.
  702.  
  703.           A. The method clone() is protected. It is protected because
  704.           cloning is an operation which the object might want to restrict
  705.           access to. If Object.clone() was declared as public, the object
  706.           could never decide to make it more restrictive later. By declaring
  707.           it protected, the object has the choice of making it *less*
  708.           restrictive.
  709.  
  710.           This means that a method can clone its own objects, but a method
  711.           cannot clone objects of another class, unless you do something
  712.           like:
  713.  
  714.           class SomeObject implements Cloneable {
  715.               public Object clone() throws CloneNotSupportedException {
  716.                   return super.clone();
  717.               }
  718.           }
  719.  
  720.           [i.e. override clone to make it public, and call the superclass
  721.           clone].
  722.  
  723.           class Foo {
  724.               Bar bar;
  725.  
  726.               Foo (Bar b) {
  727.               try {bar = (Bar) b.clone();}
  728.               catch (Exception e) {}
  729.           }
  730.           ...
  731.  
  732.           class Bar implements Cloneable {
  733.               public Object clone() throws java.lang.CloneNotSupportedException{
  734.                   return super.clone();
  735.               }
  736.           }
  737.  
  738.      3.13 How do I transform a char into the corresponding int value, that
  739.      represents the code value of the char?
  740.           A. char c = 'A';
  741.           int i = c;
  742.  
  743.           Going the other way is just
  744.  
  745.                c = (char) i;
  746.  
  747.           This question crops up so frequently because the BASIC language
  748.           uses functions to map characters into ints, ASC( 'A' ) => 65
  749.           causing BASIC programmers to seek the corresponding Java
  750.           functions. Pascal and Ada have similar functions, and no doubt
  751.           other languages too.
  752.      3.14 If I extend a class with a subclass, are the constructors
  753.      inherited?
  754.           A. "Constructor declarations are not members. They are never
  755.           inherited and therefore are not subject to hiding or overriding."
  756.           The default constructor is not inherited, but provided (see
  757.           Section 8.6.7, JLS).
  758.  
  759.           If you don't give your child class any constructors, a default
  760.           no-arg constructor that invokes the superclass' constructor is
  761.           provided for you. If the superclass doesn't have a no-arg
  762.           constructor, see 3.7
  763.      3.15 How do I allocate a multidimensional array?
  764.           A. There are several ways. If you want a rectangular array, you
  765.           can allocate the space for the array all at once. The following
  766.           creates a 4x5 array:
  767.  
  768.                int arr[][] = new int[4][5];
  769.  
  770.           If you want each row to have a different number of columns, you
  771.           can use the fact that a two-dimensional array is actually an array
  772.           of arrays. The following code allocates a triangular array:
  773.  
  774.                int arr[][] = new int[4][]; // allocate the four row arrays
  775.                for (int i = 0; i < 4; i++) // initialize each of the four rows
  776.                arr[i] = new int[i + 1]; // row i has i + 1 columns
  777.  
  778.           Note that if you allocate an array of any kind of object (as
  779.           opposed to primitive type), all the references will be null by
  780.           default. These null references can result in NullPointerExceptions
  781.           if you try to dereference them.
  782.  
  783.           In other words, after doing:
  784.  
  785.                int arr[] = new int[4];
  786.  
  787.           you can say "if (arr[2] == 0)"
  788.  
  789.           But after doing
  790.  
  791.                Integer Iarr[] = new Integer[4];
  792.  
  793.           you must fill in the object reference before using it, with e.g.
  794.  
  795.                Iarr[2] = myInt;
  796.  
  797.           or
  798.  
  799.                Iarr[2] = new Int(27);
  800.  
  801.           before you can say "if (Iarr[2].equals(myInt))"
  802.      3.16 Does it make a difference to the class file in any way, if I
  803.      import a package, versus use the full name, i.e.
  804.  
  805.           import java.rmi.server.*;
  806.           RemoteObject ro;
  807.  
  808.      versus:
  809.  
  810.           java.rmi.server.RemoteObject ro;
  811.  
  812.           A. No, it makes no difference to the class files. Import is just a
  813.           shorthand for quoting the full name package and class name (as in
  814.           the examples in the question). Importing a class does not cause
  815.           the class to be loaded at run time. There is no run time penalty
  816.           for using the * form of import. The class file will contain the
  817.           name of the packages it uses, and the loader will look for those
  818.           classes as needed at runtime.
  819.  
  820.           The different forms of import may or may not make a difference to
  821.           compile time. Such a difference is likely to be negligible, and
  822.           should not be a factor in which form of import you use.
  823.  
  824.           Some people say that stating which classes you are importing can
  825.           help program readability. In a program with many * import
  826.           statements, it may take a programmer time to find which package an
  827.           obscure class is imported from. If you explicitly list each class
  828.           you import at the top of the
  829.           program, you document which package each class you use comes from.
  830.           These people suggest that you use
  831.  
  832.                import java.rmi.server.RemoteObject;
  833.  
  834.           in preference to:
  835.  
  836.                import java.rmi.server.*;
  837.  
  838.           Other people say that it is clearer still to use the full package
  839.           and class name, at the point where you use classes in other
  840.           packages. These people suggest that you use:
  841.  
  842.                java.rmi.server.RemoteObject ro;
  843.  
  844.           But that gets a little lengthy when you instantiate:
  845.  
  846.                java.rmi.server.RemoteObject ro = new java.rmi.server.RemoteObject();
  847.  
  848.           You always have the option of stating the full package and class
  849.           name, whether you use import or not.
  850.  
  851.           Another good reason not to use the * form is when you are
  852.           importing two packages that have classes of the same name and you
  853.           want to use only one of those classes. E.g.
  854.  
  855.                import com.sun.*;
  856.                import com.ms.*;
  857.  
  858.           where there is a class called SerialPort in both those packages.
  859.           If you use the * form of import, you import both of the SerialPort
  860.           classes and then must fully qualify the class each time you use
  861.           it, to say which of the two you mean.
  862.  
  863.           In Java 1.0, if you import a class that has the same name as a
  864.           class defined in that source file, you will get an error that the
  865.           class names clash. In Java 1.1, the local class will be used when
  866.           the package name is not given; use the package name of the
  867.           imported class to use it.
  868.  
  869.           The best advice is to write the program so that it is as readable
  870.           as possible. Where you have a group of well known classes, as in
  871.           java.awt, there is no reason not to use "import java.awt.*;"
  872.      3.17 What are "class literals"?
  873.           A. A feature introduced in JDK 1.1. They are literals of type
  874.           "Class" that hold a value representing any class. There is even a
  875.           value to represent "void", like this:
  876.  
  877.           Class myCl1 = Character.class;
  878.           Class myCl2 = Void.class;
  879.           Class myCl3 = Object.class;
  880.  
  881.           You might use it like this:
  882.  
  883.           Class cl = thing.getClass();
  884.           if (cl.equals(myCl1))
  885.               System.out.println("It's a Character class");
  886.  
  887.           A class literal
  888.  
  889.                Component.class
  890.  
  891.           is the equivalent of
  892.  
  893.                Class.forName("java.awt.Component")
  894.  
  895.           The second can throw an exception, but the first cannot. If you
  896.           don't know the name of the class when you write the code, you
  897.           cannot use the first form.
  898.      3.18 How do I copy the contents of an array (with primitive type
  899.      contents) to another array?
  900.           A. Use the method java.lang.System.arraycopy(Object src, int
  901.           src_position, Object dst, int dst_position, int length);
  902.  
  903.           Note that there is no corresponding method to clear an array to
  904.           0.0, 0, null, false, '\u0000' etc (except for allocating a new
  905.           array, which will have the default initializations). This has lead
  906.           several people to suggest the old COBOL trick of "initialize by
  907.           rollup". In initialize by roll-up, the programmer sets the first
  908.           element of the array to the desired value, and then moves elements
  909.           array[0 to n-1] to array[1 to n]. Under some old IBM COBOL
  910.           compilers, code was generated to move element 0 to 1, then 1 to 2,
  911.           and so on, "rolling up" the desired value through the array. It
  912.           was always a terrible idea, as it went outside the boundaries of
  913.           defined behavior in COBOL, and was subject to being broken in any
  914.           compiler release.
  915.  
  916.           In any event, intialization by roll-up is defined not to work in
  917.           Java. If the src and dst arguments refer to the same array object,
  918.           then the copying is performed as if the components at positions
  919.           srcOffset through srcOffset+length-1 were first copied to a
  920.           temporary array with length components and then the contents of
  921.           the temporary array were copied into positions dstOffset through
  922.           dstOffset+length-1 of the argument array.
  923.  
  924.           If you simply want to clear the same array to the same value many
  925.           times, create two arrays. Fill one with the reset value, then use
  926.           System.arraycopy to copy it into the work array each time you need
  927.           to clear the work array.
  928.      3.19 What is a fast way to set all elements of an array to a given
  929.      value without duplicating the (possibly large) array?
  930.           A. Using a loop that does it one by one is probably 20 to 40 times
  931.           slower than good-old memset() in C.
  932.  
  933.           A fast way on many VM's is to set the first byte of the array,
  934.           then use System.arraycopy repeatedly to fill the next byte, the
  935.           next two bytes, the next four bytes, the next eight bytes, etc.
  936.           (Note these are not overlapping slices, so the issue raised in
  937.           Q3.18 does not
  938.           arise).
  939.  
  940.           public static void bytefill(byte[] array, byte value) {
  941.               int len = array.length;
  942.               if (len > 0)
  943.                   array[0] = value;
  944.               for (int i = 1; i < len; i += i)
  945.                  System.arraycopy( array, 0, array, i,
  946.                           ((len - i) < i) ? (len - i) : i);
  947.           }
  948.  
  949.           This is faster on Sun's VM than a simple loop, and probably faster
  950.           even under JITCs because it only performs log2(array.length)
  951.           bounds-checks at most. This is a clever code idiom applying the
  952.           binary chop algorithm to arrays whose size is not a power of 2.
  953.      3.20 Is there some declaration that I can use to make "acos", "cos",
  954.      "sin", etc. (from java.lang.Math) recognizable in my own class, so I
  955.      don't have to prefix "Math." to them?
  956.           A. No. There is no good alternative. There are several bad
  957.           alternatives:
  958.                You could wrap the functions in your own class.
  959.  
  960.                     double sin(double x) { return Math.sin(x); } // etc. for each function
  961.  
  962.                If your class does not extend another class, you could make
  963.                it extend Math, to bring the namespace in, but this is very
  964.                poor OOP style.
  965.  
  966.                If the Math class provided a public constructor -- which it
  967.                does not -- you could instantiate a local copy of Math with a
  968.                shorter name, e.g. "M".
  969.  
  970.                If java.lang.Math were not final and your class did not
  971.                extend another class, you could have your class extend Math,
  972.                to bring the namespace in. However, the final prevents this
  973.                and it is very poor OOP style to use inheritance to obtain a
  974.                trivial name abbreviation (rather than to express a type
  975.                hierarchy).
  976.           The import stament only imports packages, subpackages, and
  977.           classes. Members of classes are not imported, so
  978.  
  979.                import java.lang.Math.*;
  980.  
  981.           doesn't work.
  982.      3.21 Why does b >>>= 1 give me the same result as b >>= 1?
  983.           A. First of all, note that ">>" is a "signed" or "arithmetic"
  984.           shift, namely, it replicates the sign bit on the left as it
  985.           shifts.
  986.  
  987.           The ">>>" operator is an "unsigned" or "logical" shift; it does a
  988.           shift right and zero fill. However, there are a couple of places
  989.           where ">>>" looks like it does a signed shift!
  990.  
  991.           The issue occurs when you have a non-canonical type, byte, or
  992.           short, with a negative value, e.g.
  993.  
  994.                byte b = -15; // 0xF1
  995.                b = (byte) b >>> 4; // why isn't b 0x0f ?
  996.  
  997.           The initial expectation is that an unsigned shift right of 0xF1
  998.           would successively be (in binary) 0111_1000 then 0011_1100 then
  999.           0001_1110 then 0000_1111
  1000.  
  1001.           But that doesn't happen. The rules of arithmetic in Java say that
  1002.           all operands are converted at least to int before the operation
  1003.           (and possibly to a more capacious type). That means our byte is
  1004.           promoted to an int, so instead of shifting 0xf1, we are shifting
  1005.           0xfffffff1. If you shift right unsigned 4 places, you get
  1006.           0x0fffffff. When you cast that to a byte it becomes 0xff, or -1.
  1007.  
  1008.           The bottom line is that the final result is the same as if you'd
  1009.           performed the signed shift because the unsigned shift applied to
  1010.           the intermediate int, not to the original byte. This anomaly means
  1011.           that ">>>" is useless for negative bytes and shorts. It is
  1012.           probably safer and clearer not to use it at all, but to mask and
  1013.           shift like this:
  1014.  
  1015.                // not recommended
  1016.                byte b = -15;
  1017.                b = (byte) (b>>>4);
  1018.                System.out.println("b= "+Integer.toHexString(b) );
  1019.  
  1020.                // recommended
  1021.  
  1022.                b= -15;
  1023.                b = (byte) ( (b & 0xFF) >> 4 );
  1024.                System.out.println("b= "+Integer.toHexString(b) );
  1025.  
  1026.      3.22 How do I compare two Strings together?
  1027.  
  1028.           if (s1 == s2)
  1029.  
  1030.           is giving me funny results.
  1031.  
  1032.           A. The comparison using "==" on objects, like Strings, is asking
  1033.           the question "do these two objects have the same reference?". That
  1034.           is, do they have the same address, and hence are the same object?
  1035.           What you really want to do is ask "do these two Strings have the
  1036.           same *contents*?"
  1037.  
  1038.           You do that with any of (and there are others too)
  1039.  
  1040.                if (s1.equals(s2) )
  1041.  
  1042.                or if (s1.equalsIgnoreCase(s2) )
  1043.                or if (s1.startsWith(s2) )
  1044.                or if (s1.endsWith(s2) )
  1045.                or if (s1.regionMatches(s1_offset, s2, s2_offset, length) )
  1046.                or if (s1.compareTo(s2) < 0)
  1047.  
  1048.           Note that you can do this with literals:
  1049.  
  1050.                if ("apple".equals(s2) ) ...
  1051.  
  1052.           If you compare these the other way round, like this:
  1053.  
  1054.                if ( s2.equals("apple") ) ...
  1055.  
  1056.           and s2 is null, you will get a null pointer exception. Be alert to
  1057.           this.
  1058.  
  1059.                                    -----------------
  1060.  
  1061. 4. AWT and Related Topics
  1062.  
  1063.      4.0 AWT
  1064.  
  1065.      4.0.1 Why do I get this when using JDK 1.1 under X Windows?
  1066.  
  1067.                java.lang.NullPointerException
  1068.                at sun.awt.motif.MFramePeer.<init>(MFramePeer.java:59)
  1069.                at sun.awt.motif.MToolkit.createFrame(MToolkit.java:153)
  1070.                at java.awt.Frame.addNotify(Frame.java)
  1071.                at java.awt.Window.pack(Window.java)
  1072.  
  1073.           A. There's a missing font on your system. Move font.properties
  1074.           from the "lib" subdirectory aside to font.properties.bak Then it
  1075.           won't look for the font and fail to find it.
  1076.  
  1077.           The problem occurs because the Motif AWT libraries use the Font
  1078.           "plain Dialog 12 point" as a fall-back default font.
  1079.           Unfortunately, when using a remote X server sometimes this font
  1080.           isn't
  1081.           available.
  1082.  
  1083.           On an X-terminal, the diagnostic may be slightly different, a segv
  1084.  
  1085.                % appletviewer HelloWorldApplet.html
  1086.                SIGSEGV 11* segmentation violation
  1087.                si_signo [11]: SIGSEGV 11* segmentation violation
  1088.                si_errno [0]: Error 0
  1089.                si_code [1]: SEGV_ACCERR [addr: 0x14]
  1090.  
  1091.           To determine which fonts you have, issue a command such as
  1092.                xlsfonts > ~/fonts.txt
  1093.           Then pick through the long list of fonts to determine which ones
  1094.           you want to use. The xfd program will let you look at a font:
  1095.                xfd -fn "your font name here" &
  1096.      4.0.2 Why is GridBagLayout so hard to use?
  1097.           A. GridBagLayout was contributed to Javasoft by a programmer who
  1098.           wanted to support the Java effort. It was intended as a proof that
  1099.           the AWT offered enough features for programmers to write their own
  1100.           layout managers. It wasn't designed with human factors and ease of
  1101.           use in mind. If it bothers you (it bothers me) then just don't use
  1102.           it. Create your GUI on several panels and use the other layout
  1103.           managers as appropriate to get the exact effect you want. The
  1104.           official story from the project leader of the AWT project, as
  1105.           explained to the Mountain View Java Users' Group on Dec 4 1996,
  1106.           is:
  1107.                "The case has been made and is now accepted that
  1108.                GridBagLayout is too hard to use for what it offers. GBL will
  1109.                continue to be supported, and something better and simpler
  1110.                will eventually be provided as well. This "better GBL" can be
  1111.                used instead of GBL."
  1112.           Bottom line: nobody has to waste any effort on GBL, there are
  1113.           better alternatives available now, and it will be replaced by the
  1114.           SwingSet "SpringLayout" Springs & Struts style layout manager to
  1115.           be introduced as part of the Java Foundation Classes with JDK 1.2.
  1116.      4.0.3 How do you change the font type and size of text in a TextArea?
  1117.           A. myTextArea.setFont(new Font("NAME", <STYLE>, <SIZE>));
  1118.                where:
  1119.                     NAME is the name of the font (eg Dialog or TimesRoman).
  1120.                     <STYLE> is Font.PLAIN, Font.ITALIC, Font.BOLD or any
  1121.                     additive combination (e.g. Font.ITALIC+Font.BOLD).
  1122.                     <SIZE> is the size of the font, e.g. 12. e.g. new
  1123.                     Font("TimesRoman", Font.PLAIN, 18);
  1124.      4.0.4 Can you have different fonts for individual words in a TextArea ?
  1125.           A. No. If you're trying to write a word processor, use the Canvas
  1126.           class to render on.
  1127.      4.0.5 How much text can be put in a TextArea?
  1128.           A. TextArea just uses the corresponding widget of the underlying
  1129.           window system. It will be bounded by the limit imposed in the
  1130.           native window system. In Windows95 TextAreas can hold about
  1131.           28Kbytes. The native widget allows 32Kb, but there is some
  1132.           overhead which reduces the amount available to the programmer.
  1133.      4.0.6 MyClass works fine except when I try to set a particular font. I
  1134.      just can't seem to get it to work in Win95, but I can get it to work on
  1135.      a MacOS and Unix.
  1136.           A. You probably specified a font name that isn't available under
  1137.           your Win95; this is one of those cross-platform differences that
  1138.           can bite you if you over-specify for one platform, like specifying
  1139.           "Arial" as a font and expecting it to work on something other than
  1140.           Windows.
  1141.  
  1142.           On both Windows 95 and Solaris 2.6, these fonts
  1143.                Dialog
  1144.                SansSerif
  1145.                Serif
  1146.                Monospaced
  1147.                Helvetica
  1148.                TimesRoman
  1149.                Courier
  1150.                DialogInput
  1151.                ZapfDingbats
  1152.           are revealed by this code:
  1153.  
  1154.                import java.awt.*;
  1155.  
  1156.                class foonly {
  1157.                   static public void main(String s[])
  1158.                   {
  1159.                       String n[]= new Frame().getToolkit().getFontList();
  1160.                       for (int i=0;i<n.length; i++)
  1161.                          System.out.println(n[i]);
  1162.  
  1163.                       System.exit(0);
  1164.                   }
  1165.                }
  1166.  
  1167.                In other words, You can get a String array of the names of
  1168.                the fonts by
  1169.  
  1170.                     String[] fonts = Toolkit.getDefaultToolkit().getFontList()
  1171.  
  1172.      4.0.7 Is it possible to draw a polygon or a line more than 1 pixel
  1173.      wide?
  1174.           A. JDK 1.1.1 doesn't have support for this. The standard
  1175.           workaround for drawing a thick line is to draw a filled polygon.
  1176.           The standard workaround for drawing a thick polygon is to draw
  1177.           several polygons.
  1178.  
  1179.           There is a useful class at
  1180.           http://www.apl.jhu.edu/~hall/java/GraphicsUtil.html It extends the
  1181.           drawxxx and fillxxx methods of java.awt.Graphics. It adds a Line
  1182.           Width argument to most of the drawxxx methods, a Color argument to
  1183.           most of the drawxxx and fillxxx methods, and a Font argument to
  1184.           draw String and drawChars.
  1185.      4.0.8 I use add(Component) to add Components to the Container. Is there
  1186.      any way to explicitly set the z-order of these Components?
  1187.           A. JDK 1.0 has no way to explicitly set the z-order of components.
  1188.           You can try it heuristically, based on the browser you're using,
  1189.           or you can use CardLayoutManager to ensure the panel you want is
  1190.           at the front.
  1191.  
  1192.           In JDK 1.1 the z-order of components ("z-order" means
  1193.           "front-to-back" order, i.e. which window is in front of which) can
  1194.           be controlled by using the the method add(Component comp, int
  1195.           index). By default, components are added 0 to N. The method paint
  1196.           of class Container paints its visible components from N to 0.
  1197.      4.0.9 When I call repaint() repeatedly, half my requests get lost and
  1198.      don't appear on the screen. Why is this?
  1199.           A. repaint() just tells the AWT that you'd like a paint to happen.
  1200.           AWT will fold several adjacent repaint requests into one, so that
  1201.           only the most current paint is done. One possible workaround might
  1202.           be to use a clip rectangle and only paint the different areas that
  1203.           have changed.
  1204.      4.0.10 What is the difference between
  1205.                Component's setForeground(Color c)
  1206.           and
  1207.                Graphics's setColor(Color c) ?
  1208.           A. First of all, these methods do the same thing: set the
  1209.           foreground color to the value of the parameter. The difference
  1210.           lies in where you use them. There is also a
  1211.           Component.setBackground that will set the background color.
  1212.  
  1213.           If you are in a constructor or an event handler (e.g. "click here
  1214.           to turn the canvas blue") you have a Component and should use the
  1215.           setForeground() method. If you are in a paint() method, that takes
  1216.           a Graphics context as its argument so you will typically use
  1217.           g.setColor(c).
  1218.  
  1219.           Unlike a Component, a Graphics object doesn't have a background
  1220.           color and a foreground color that you can change independently. A
  1221.           Graphics object arrives in the color(s) inherited from the drawing
  1222.           surface. From then on, any rendering (drawLine(), drawRect(),
  1223.           fillOval(), etc.) will be
  1224.           done in the setColor() color. Because they do different things,
  1225.           the Component and Graphics methods have different names.
  1226.      4.0.11 When I start a mouse drag inside a Component, and go outside the
  1227.      Component, still dragging, the mouse events still get sent to the
  1228.      Component, even though I am outside it. Is this a bug?
  1229.           A. No, it is the specified behavior. The java API documentation
  1230.           says:
  1231.                "... Mouse drag events continue to get sent to this component
  1232.                even when the mouse has left the bounds of the component. The
  1233.                drag events continue until a mouse up event occurs. ..."
  1234.           It is done for the convenience and ease of the application
  1235.           programmer. It allows you to handle all drags from the place of
  1236.           origin. If you don't want this, simply look at the coordinates of
  1237.           the mouseDrag Event, and if they are outside the Component, ignore
  1238.           them.
  1239.      4.0.12 What's all this about subclassing Canvas and overriding paint()
  1240.      ? Can't I just do a getGraphics() for a component, and draw directly on
  1241.      that?
  1242.           A. You can do that, and it might work up to a point (or it might
  1243.           not). A problem arises when the window system wants to refresh
  1244.           that component e.g. because it has been partially obscured and is
  1245.           now revealed. It calls paint(), and that has no knowledge of the
  1246.           other g.drawing() you have done.
  1247.      4.0.13 But couldn't the AWT just remember what has been drawn to a
  1248.      Graphics context, and replicate that instead of calling paint()?
  1249.           A. It could, but that is not how it works. In practice it is a lot
  1250.           simpler to be able to look at the paint method, and see explicitly
  1251.           all the things that will be done to draw that component. Bottom
  1252.           line: use paint(), not g=getGraphics(); g.drawString( ...
  1253.      4.0.14 How can I get the dimensions and resolution of the screen?
  1254.           A. java.awt.Toolkit.getDefaultToolkit().getScreenSize()
  1255.           java.awt.Toolkit.getDefaultToolkit().getScreenResolution()
  1256.  
  1257.           Screen resolution is in dots-per-inch.
  1258.  
  1259.           Take a look in the Toolkit class for other useful methods.
  1260.  
  1261.           Toolkit.getDefaultToolkit().getColorModel().getPixelSize() gets
  1262.           you the color model in terms of bits per pixel.
  1263.  
  1264.           Math.pow(2,Toolkit.getDefaultToolkit().getColorModel().getPixelSize())
  1265.           gets you the color model in terms of number of colors. Or use
  1266.           this:
  1267.                1 <<
  1268.                Toolkit.getDefaultToolkit().getColorModel().getPixelSize()
  1269.           That does a shift left to calculate the power of two.
  1270.      4.0.15 How do I allow for the size of the title bar and border when I
  1271.      draw a Frame?
  1272.           A. Use MyFrame.getInsets(). This returns a java.awt.Insets object
  1273.           which has four ints: top, left, bottom, right, giving the number
  1274.           of pixels each of those margins are inset from the top. You can
  1275.           use these value to adjust the Dimension object returned by
  1276.           component.getSize().
  1277.      4.0.16 When I run the Swing demo on Win95 I get an error "Out of
  1278.      environment space"
  1279.           A. That's because you don't have enough space for your DOS
  1280.           environment. You can fix this with:
  1281.              + Right click your MS-DOS Prompt icon or window and choose
  1282.                Properties.
  1283.              + Choose "Memory" and on "Initial Environment" choose 4096
  1284.                instead of "auto".
  1285.              + Run Swing again, you'll be OK.
  1286.      4.0.17 How do I resize a List? I had a List defined as
  1287.  
  1288.           List tlist = new List(10);
  1289.  
  1290.      but the Strings in the list were 80 characters long and only the first
  1291.      15 were being shown. I was not able to resize the List to display the
  1292.      contents without using the scroll bar.
  1293.           A. A List cannot be resized in a constructor, so add the following
  1294.           to the Applet (or wherever)
  1295.  
  1296.                public void paint (Graphics g) {
  1297.                tlist.setSize(200,200);
  1298.                }
  1299.  
  1300.           Then before showing panel/frame with the List:
  1301.  
  1302.                tlist.resize(400,400);
  1303.  
  1304.      4.0.18 How can my program tell when a window is resized?
  1305.           A. Override the setBounds() method of Component to do what you
  1306.           want. Of course, have it call super.setBounds() as well. Note that
  1307.           setBounds() replaces reshape() which is deprecated.
  1308.  
  1309.           Note the new APIs call the deprecated APIs instead of the other
  1310.           way round. For example, Component.setBounds calls
  1311.           Component.reshape, instead of reshape calling setBounds.
  1312.      4.0.19 Why doesn't my window  close when I click on the X in the title
  1313.      bar?
  1314.           A. Here's how to make your program do that.
  1315.           JDK 1.0.2: Handle Event.WINDOW_DESTROY to do a hide() and
  1316.           dispose() on the Frame.
  1317.  
  1318.           JDK 1.1:
  1319.           a) Listen for WindowEvent and do hide(); dispose(); in
  1320.           windowClosing() - this ought to be the "default" behaviour.
  1321.           b) enable AWTEvent.WINDOW_CLOSING and do the hide() and dispose()
  1322.           in processWindowEvent().
  1323.      4.0.20 How do I clear the contents of a TextArea?
  1324.           A. Set it to a null String with this:
  1325.  
  1326.                area.setText("");
  1327.  
  1328.      4.0.21 What are those preferredSize() and minimumSize() methods in
  1329.      Component?
  1330.           A. Those methods allow a LayoutManager to calculate the preferred
  1331.           and minimum sizes of the Components it is arranging. You can
  1332.           control the values that the LayoutManager gets by creating
  1333.           subclasses of the Components you are using and overriding these
  1334.           methods.
  1335.      4.0.22 How can I force a synchronization of the graphics state, e.g. of
  1336.      a cursor change, or an animation frame to be rendered?
  1337.           A. This is done by the sync() method in the toolkit. So just use:
  1338.  
  1339.                AnyComponent.getToolkit().sync();
  1340.  
  1341.      4.0.23 How do I plot a single pixel to the screen?
  1342.           A. Use g.drawLine(x1,y1,x1,y1) to draw a line one pixel in length.
  1343.           If you are drawing a very large number of individual pixels,
  1344.           consider using a java.awt.MemoryImageSource object and measure
  1345.           whether this offers better performance.
  1346.      4.0.24 How can I tab between components?
  1347.           A. In JDK 1.0, you have to read the key press, and program it
  1348.           explicitly. JDK 1.1 supports tab and shift-tab (previous field)
  1349.           automatically. The tab order is the order that the components were
  1350.           added to the container.
  1351.      4.0.25  What is the difference between "low level" and "semantic"
  1352.      events?
  1353.           A.It doesn't seem to be a distinction that is of use to the
  1354.           programmer. Semantic events are those generated when you frob a
  1355.           control (move a scrollbar, click on a button, select from a menu,
  1356.           etc). Low-level events are the others (resizing a window, dragging
  1357.           the mouse, striking a key, adding a Component to a Container,
  1358.           etc).
  1359.  
  1360.           Low level events: use the method enableEvents() and override
  1361.           performX() for those events in the object itself.
  1362.           Semantic events: Uses the method addXListener() to add objects
  1363.           which implement the XListener interface in order to get XEvent
  1364.           objects delivered (usually via the AWTEventMulticaster).
  1365.      4.0.26 Is it possible to have a Java window float above all other
  1366.      windows. for example a tool palette floats in a super-layer always
  1367.      above all the regular document windows on which you use the palette's
  1368.      tools?
  1369.           A. On MS Windows, a Window object floats above all other windows,
  1370.           unlike a Frame, which is layered in with ordinary windows. This
  1371.           behavior yields a "floating" effect. Whether a Window object is
  1372.           really supposed to float is another question entirely.
  1373.  
  1374.           On Mac, a Window object is either layered in with other windows,
  1375.           just like a Frame is, or else it is entirely modal -- depending on
  1376.           which VM you use. In Java -- there appears to be no easy way to
  1377.           get floating behavior. If anyone knows otherwise, please send in
  1378.           your comments.
  1379.      4.0.27 How do I center a dialog box?
  1380.           A. You cannot currently get the applet's absolute screen
  1381.           coordinates. Its location (0,0) is relative to the browser, not
  1382.           the screen itself. But you can center something that it pops up or
  1383.           displays centered on the screen with code like this:
  1384.  
  1385.           Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
  1386.           my_window.move(
  1387.                   ( screen.width -  window.size().width ) / 2,
  1388.                   ( screen.height - window.size().height ) / 2 );
  1389.  
  1390.           my_window.show().
  1391.  
  1392.           In a related fashion, you can center something on its parent like
  1393.           this. Note the intelligent use of APIs like translate() to do the
  1394.           work for you.
  1395.  
  1396.           void centre(Component parent) {
  1397.               pack();
  1398.  
  1399.               Point p = parent.getLocation();
  1400.               Dimension d = parent.getSize();
  1401.               Dimension s = getSize();
  1402.  
  1403.               p.translate((d.width - s.width) / 2, (d.height - s.height) / 2);
  1404.               setLocation(p);
  1405.           }
  1406.  
  1407.      4.0.28 How do I get back to a normal echo after I have used
  1408.      TextField.setEchoChar('*');
  1409.           A. TextField.setEchoChar('\0') works on most Windows based
  1410.           browsers... but for most other platforms (ie: Netscape under
  1411.           UNIX), it just locks up the textfield.
  1412.  
  1413.           There is only one good solution, and that is to make two
  1414.           TextFields on top of each other, one normal, and one with
  1415.           .setEchoChar('*'), and switch between them.
  1416.  
  1417. 4.1 APPLETS
  1418.  
  1419.      4.1.1 What is the difference between an application, and applet and a
  1420.      servlet?
  1421.           A. An application is a standalone program. An applet is a
  1422.           downloadable program that runs in a web-browser. Typically an
  1423.           applet has restricted access to the client system for reasons of
  1424.           security.
  1425.  
  1426.           A Servlet is an application, but (like an applet) requires a
  1427.           context in which to run, namely web-server software. Servlets are
  1428.           used like CGI, but allow the server end to be written in Java as
  1429.           well as the client.
  1430.  
  1431.           The Web Server starts up a servlet when the URL is referenced, and
  1432.           now your applets have something that they can talk to (via
  1433.           sockets) on the server that can write files, open connections to
  1434.           other servers, or whatever.
  1435.  
  1436.           Don't confuse Sun's JWS "Java Web Server" with JWS "Java
  1437.           Workshop". Java Web Server supports servlets as does the
  1438.           lightweight and free server at Acme.com:
  1439.                http://www.acme.com/java/software/Acme.Serve.Serve.html
  1440.      4.1.2 My applet works on my machine, but fails when I put it on our web
  1441.      server. Why?
  1442.           A. It could be one of several reasons, and unfortunately the
  1443.           messages that you get in this situation aren't much help. In
  1444.           general, you can assume that either your applet's class files are
  1445.           corrupted somehow, or the web server can't find one or more of
  1446.           them when the browser needs them.
  1447.  
  1448.           Be careful of the following things:
  1449.              + Make sure you transfer the class files in binary mode, rather
  1450.                than text or ASCII mode.
  1451.              + Make sure you transfer *all* of the class files which are a
  1452.                part of your applet. Sometimes people are surprised by how
  1453.                many there are. There will be a class file for every class
  1454.                and interface you define, even if you define more than one in
  1455.                a single source file. If you use the Java 1.1 "inner classes"
  1456.                feature, there will be class files for each inner class as
  1457.                well.
  1458.              + Make sure you maintain the appropriate case distinctions in
  1459.                your filenames. If a class is called StUdLy, it must be found
  1460.                in a file called StUdLy.class.
  1461.              + Make sure you maintain the directory structure that matches
  1462.                your package structure. If you declare a class in package
  1463.                COM.foo.util, the class file needs to be in directory
  1464.                COM/foo/util under the applet's codebase directory. Again,
  1465.                case distinctions are important for package/directory names,
  1466.                just as they are for class/file names.
  1467.              + Make sure that the web server process will have read access
  1468.                to the class files, and search access to the directories that
  1469.                the files are in. For example, if the web server runs on a
  1470.                Unix machine, use the command "chmod o+r filename" for the
  1471.                files, and "chmod o+x dirname" for the directories.
  1472.      4.1.3 How do I use an image as the background to my applet? How do I
  1473.      set the background color of my applet the same as the browser?
  1474.           A. You can simply do a g.drawImage(yourImage, x,y, this) in the
  1475.           paint() routine of your applet. If the image isn't big enough to
  1476.           fill the entire background, tile it or scale it There is some code
  1477.           to tile at:
  1478.                http://www.geocities.com/SiliconValley/Vista/1337/
  1479.           (under AWT) Alternatively, the AWT can scale your background image
  1480.           to the size of
  1481.           the applet. The result quality will depend on the kind of image.
  1482.           Inside an applet class, you can use:
  1483.  
  1484.                drawImage(img, 0, 0, size().width, size().height, this);
  1485.  
  1486.           You can set the background color to match the background color of
  1487.           the browser by passing the value in as a parameter, like this:
  1488.  
  1489.           In the HTML applet tag:
  1490.                param name=BrowserColor value=F1F1F1
  1491.                (value should be the same hex as the HTML COLOR value).
  1492.                In the Applet init() method:
  1493.  
  1494.                String colparam = getParameter("BrowserColor");
  1495.                int col = Integer.valueOf(colparam,16).intValue();
  1496.                setBackground( new Color(col) );
  1497.  
  1498.           An applet cannot override the size imposed by the HTML. If you
  1499.           make the applet larger, the browser will still clip to the
  1500.           origional size. If you need more room, open up a new Frame, Window
  1501.           or Dialog to show your output.
  1502.      4.1.4 how do you make the applet's background transparent?
  1503.           A. there is no way to give an applet a transparent background that
  1504.           lets the web browser background show through. You can simulate it
  1505.           by giving the applet a background that matches the underlying
  1506.           browser background. It doesn't produce satisfactory results with a
  1507.           patterned background because of problems aligning the edges.
  1508.  
  1509.           Lightweight components (new in JDK 1.1) have a transparent
  1510.           background.
  1511.      4.1.5 How do you do file I/O from an applet?
  1512.           A. See answer to question 6.8.
  1513.      4.1.6 How do you get a MenuBar/Menu in an applet?
  1514.           A. In your applet's init() method, create a Frame instance and
  1515.           then attach the Menus, Menubar etc to that frame. You cannot
  1516.           attach the Menu or a Menubar to an applet directly.
  1517.  
  1518.           Or get the parent Frame like this:
  1519.  
  1520.                Container parent = getParent();
  1521.                while (! (parent instanceof Frame) )
  1522.                    parent = parent.getParent();
  1523.  
  1524.                Frame theFrame = (Frame) parent;
  1525.  
  1526.           This second suggestion probably won't work on Macs (where would
  1527.           the menubar go?) or in some browsers. In JDK 1.1, just use a popup
  1528.           menu, which isn't attached to a Frame.
  1529.      4.1.7 Can I get rid of the message "Warning:Applet Window" along the
  1530.      bottom of my popup windows in my Applet?
  1531.           A. This is a security feature that prevents the applet programmer
  1532.           from popping up a window that looks like it came from the native
  1533.           OS and asking for passwords or credit card info (etc). Users must
  1534.           always be aware of when they are talking to an unsigned applet.
  1535.           You can get rid of it by signing the applet, if the user accepts
  1536.           signed applets from you.
  1537.  
  1538.           In Netscape (only), using the Capabilities API to make the call
  1539.  
  1540.                PrivilegeManager.enablePrivilege("UniversalTopLevelWindow");
  1541.  
  1542.           before creation of the Frame eliminates the message, if the
  1543.           security manager passes it.
  1544.      4.1.8 When I subclass Applet, why should I put setup code in the init()
  1545.      method? Why not just a constructor for my class?
  1546.           A. The browser invokes your constructor, then setStub, then
  1547.           init(). Hence when your constructor is invoked, the AppletStub
  1548.           (and through it the AppletContext) is not yet available. Although
  1549.           in principle you can do things in the constructor that don't rely
  1550.           (even indirectly) on the AppletStub or AppletContext, it is less
  1551.           error-prone to simply defer all setup to the init method. That way
  1552.           you know that anything that needs the stub/context will have it
  1553.           available.
  1554.      4.1.9 How do I pull a non-class file, such as a .gif, out of a jar
  1555.      file?
  1556.           A. In your class, you should be able to do something like this:
  1557.  
  1558.                String imageFileName = "foo.jpg"
  1559.                URL imageURL = getClass().getResource(imageFileName);
  1560.  
  1561.                Toolkit tk = Toolkit.getDefaultToolkit();
  1562.  
  1563.                Image img = null;
  1564.                try {
  1565.                    img = tk.createImage((java.awt.image.ImageProducer)
  1566.                    imageURL.getContent());
  1567.                }
  1568.                catch (java.io.IOException ex) {
  1569.                    System.out.println(ex);
  1570.                }
  1571.  
  1572.           (Like anything involving Jar files, this is from JDK 1.1 on).
  1573.      4.1.10 I want to know about {applets,applications} but the lousy book I
  1574.      got just talks about {applications,applets}. What can I do?
  1575.           A. The truth is that 95% of the material is the same, whichever
  1576.           your book chooses to focus on. Some people write their apps to
  1577.           work completely in a Panel, then depending on whether they're
  1578.           running stand-alone or in a browser the Panel is either added to a
  1579.           Frame or an Applet. The trick is that you need to subclass the
  1580.           application's Frame in order to handle the WINDOW_CLOSING
  1581.           (previously WINDOW_DESTROY) event yourself. If you fail to do
  1582.           this, when running as an application, the window won't close.
  1583.  
  1584.           In this scenario the following code will tell you which
  1585.           environment you're running in:
  1586.  
  1587.                public boolean isRunningInBrowser() {
  1588.                   Component p = getParent();
  1589.  
  1590.                   while(p != null && !(p instanceof Frame)) {
  1591.                      p = p.getParent();
  1592.                   }
  1593.  
  1594.                   return (p == null);
  1595.                }
  1596.  
  1597.      4.1.11 How do I print a page with an applet?
  1598.           A. iBrowsers are starting to introduce support for this. Until
  1599.           they all have it, your best bet is to print a screendump.  Using
  1600.           the browser to print the page may leave a blank where the applet
  1601.           is.  Putting print support in the applet will print the applet
  1602.           only, not the rest of the browser page.
  1603.  
  1604.      4.1.12  How can I position my dialogs centered (not top left)?
  1605.           A.  Use some code like this:
  1606.                void centre(Component parent) {
  1607.                           pack();
  1608.  
  1609.                           Point p = parent.getLocation();
  1610.                           Dimension d = parent.getSize();
  1611.                           Dimension s = getSize();
  1612.  
  1613.                           p.translate((d.width - s.width) / 2, (d.height -
  1614.           s.height) / 2);
  1615.                     setLocation(p);
  1616.               }
  1617.  
  1618.      4.1.13  How can I get two applets on the same page to communicate with
  1619.      each other? centered
  1620.           A.(Easy way) Make them into one applet with two GUIs. (Harder) Use
  1621.           the static members of a common class to communicate information
  1622.           between the applets. This is something of a hack as it relies on
  1623.           class-loading behavior that may change in future. Try to avoid the
  1624.           need for applets to talk to each other. Also check the URL
  1625.           http://java.sun.com:81/products/hotjava/1.1/applet_environment.html
  1626.           which explains how it can be done in HotJava 1.1. Recommendation:
  1627.           stay far away from code which is browser-specific.
  1628.  
  1629. 4.2 BROWSERS
  1630.  
  1631.      4.2.1 When will my favorite browser support Java 1.1?
  1632.           A: Netscape Communicator 4.0 with the feature patch supports most
  1633.           new features of Java 1.1, and Netscape has committed to the rest.
  1634.           Communicator is scheduled to fully support Java 1.1 in late 1997.
  1635.                URL:
  1636.                http://developer.netscape.com/support/faqs/champions/java.html#21
  1637.           Sun's HotJava browser fully supports the JDK 1.1 features.
  1638.  
  1639.           Internet Explorer 4.0, released in September 1997, does not fully
  1640.           support Java 1.1, omitting entirely RMI, JNI, signed JARs, and
  1641.           making around 50 non-standard modifications to the java.awt.* and
  1642.           other package. After weeks of negotiations, Sun has brought a
  1643.           breach of contract lawsuit against Microsoft because of the
  1644.           unauthorized changes. Programmers who support Java are recommended
  1645.           not to use Internet Explorer until Microsoft brings it back into
  1646.           compliance with the Java standard.
  1647.  
  1648.           Microsoft is trying to slow down the drive to Java, by spreading
  1649.           fear, uncertainty, doubt, and trying to fragment the Java
  1650.           environment. People say that sooner or later Microsoft will be
  1651.           forced to support portable Java, not try to undermine it. Until
  1652.           that day, developers should avoid Microsoft's near-Java knock-off
  1653.           when they choose their development tools.
  1654.  
  1655.      4.2.2 Is it possible to set and retrieve cookies from Java, in a manner
  1656.      that is compatible with all browsers supporting cookies?
  1657.           A. Short answer: no.
  1658.           Longer answer: probably no.
  1659.           Ultimate answer:
  1660.           A cookie is a morsel of tasty data that a server sends back to the
  1661.           client, and can retrieve on demand. It allows the server to retain
  1662.           some state information for each of its clients. The information is
  1663.           typically something like "what pages has the user seen?" or "is
  1664.           this a privileged user?".
  1665.  
  1666.           The DevEdge site on Netscape's home page has a javascript-java
  1667.           example on getting cookies. It's quite involved. Stick to just
  1668.           Java if you can.
  1669.      4.2.3 I am developing an applet and testing it in Netscape Navigator. I
  1670.      find that after I recompile, I press reload, clear the caches, retype
  1671.      the URL of the HTML wrapper, and I still have the old version. Why is
  1672.      this?
  1673.           A. It is because Netscape has completely failed to improve the
  1674.           defective code that does this monstrously wrong thing. It has been
  1675.           like this for many successive releases.
  1676.  
  1677.           Flushing the network cache will make no difference; that isn't
  1678.           where the caching is taking place. Although applets are sometimes
  1679.           "pruned" and their ClassLoaders garbage-collected, this doesn't
  1680.           happen predictably, so restarting Netscape is the only reliable
  1681.           work-around at the moment.
  1682.  
  1683.           A related question is "how do I make the browser reload from a
  1684.           URLConnection instead of just getting the content from the local
  1685.           cache?" The answer is to use
  1686.           java.net.URLConnection.setUseCaches(false)
  1687.           Browsers seem to vary in their conformance to this programmatic
  1688.           request. Netscape caching varies depending on whether a proxy
  1689.           server is in use, and which thread in the applet made the get
  1690.           request.
  1691.      4.2.4 So, why can't Netscape reload the applet when you press the
  1692.      Reload button?
  1693.           A. For the applet to be reloaded, the new version would have to be
  1694.           loaded in a different ClassLoader. Navigator/Communicator's policy
  1695.           for assigning ClassLoaders to applets doesn't take into account
  1696.           whether a reload has been done (although there is no technical
  1697.           reason why it couldn't).
  1698.  
  1699.           Some versions of Netscape reload the Applet if you hold down
  1700.           <Shift> while you click on reload. Until they fix it, use the
  1701.           appletviewer to test applets. And send them mail -- developers can
  1702.           only fix the bugs they know about.
  1703.      4.2.5 Should I use Microsoft CAB files or Java JAR files?
  1704.           A. The question contains its own answer.
  1705.  
  1706.           CAB format is a Microsoft-only format. So do not use it as it
  1707.           destroys software portability.
  1708.  
  1709.           JAR format is the Java standard format, based on PKZIP format
  1710.           including data compression. JARs were introduced with JDK 1.1
  1711.  
  1712.           See http://www.ibm.com/java/community/viewarchive4.html for more
  1713.           information.
  1714.  
  1715.           You should use the Java standard format JAR (Java Archive) files,
  1716.           not a vendor-specific format. JAR files are not just a Java
  1717.           standard, they are in industry-standard PKZIP format. One reader
  1718.           comments that both formats can be used with this tag:
  1719.                <APPLET NAME=myapplet
  1720.                ARCHIVE="myzip.zip"
  1721.                CODE="com/nnnnn/nnnn/cccccccc.class"
  1722.                WIDTH=n
  1723.                HEIGHT=n>
  1724.                <PARAM NAME="cabbase" VALUE="mycab.cab">
  1725.                </APPLET>
  1726.           IE3 does not support JAR
  1727.           IE4 supports compressed and uncompressed JAR, but not signed JAR
  1728.           IE3 and IE4 both support CAB (signed & unsigned)
  1729.                                    -----------------
  1730.  
  1731. 5. CORE LIBRARIES
  1732.  
  1733.      5.1 I can't seem to change the value of an Integer object once created.
  1734.           A. Correct. Integer (Float, Double, etc) are intended as an object
  1735.  
  1736.           wrapper for a specific value of a number, not as a general purpose
  1737.  
  1738.           way of shipping a primitive variable around as an Object. If you
  1739.           need
  1740.           that it's easy enough to create: class General { public int i; }
  1741.      5.2 How do I print from a Java program?
  1742.           A. Use the Toolkit.getPrintJob() method
  1743.  
  1744.                Component c = this.getParent();
  1745.                while (c!=null && !(c instanceof Frame))
  1746.                   c=c.getParent();
  1747.  
  1748.                PrintJob pj = getToolkit().getPrintJob((Frame) c, "test", null);
  1749.                Graphics pg = pj.getGraphics();
  1750.                printAll(pg);
  1751.                pg.dispose();
  1752.                pj.end();
  1753.  
  1754.           This feature was introduced with JDK 1.1. A common place to put
  1755.           this is in the code that handles a button press. Printing from an
  1756.           untrusted applet is subject to a check from the SecurityManager.
  1757.  
  1758.           To print in JDK 1.0.2, some people have suggested using Jentec's
  1759.           JENI. (The Java Enterprise Network Interface). JENI is a set of
  1760.           classes that provides applets with file, print, email, and
  1761.           directory services to lots of different protocols and locally
  1762.           without the applet having to change or even be aware which is
  1763.           being used.
  1764.  
  1765.           JENI is free and available at http://www.jentec.com. For an
  1766.           example of how to print, see
  1767.           http://www.jentec.com/live/jeni/PrintingAFile.html. To save a
  1768.           file, see
  1769.           http://www.jentec.com/live/jeni/CreatingAFile.html.
  1770.      5.3 What are the properties that can be used in a PrintJob?
  1771.           A. The properties are
  1772.                awt.print.destination - can be "printer" or "file"
  1773.                awt.print.printer - print command
  1774.                awt.print.fileName - name of the file to print
  1775.                awt.print.numCopies - obvious
  1776.                awt.print.options - options to pass to the print command
  1777.                awt.print.orientation - can be "portrait" or "landscape"
  1778.                awt.print.paperSize - can be "letter","legal","executive" or
  1779.                "a4"
  1780.  
  1781.                The defaults are destination=printer, orientation=portrait,
  1782.                paperSize=letter, and numCopies=1
  1783.  
  1784.                You can search for info like this by joining the Java
  1785.                Developer Connection (it's free)
  1786.  
  1787.                http://developer.javasoft.com/developer/index.html
  1788.  
  1789.                Then do a search for "PrintJob".
  1790.      5.4 Is there any package in Java to handle HTML?
  1791.           A. See the answer to Question 8.14
  1792.      5.5 Why don't Dialogs work the way I want them to?
  1793.           A. Modal dialogs (dialog windows that stay up until you click on
  1794.           them) are buggy in many browsers and in the 1.0.2 JDK. One bug is
  1795.           that the dialog is not necessarily put on top when it is
  1796.           displayed. Most of the modal dialog bugs are fixed in JDK 1.1.
  1797.      5.6 Where can I find information about the sun.* classes in the JDK?
  1798.           A. You're not supposed to. Those classes are only to support
  1799.           functions in the java.* hierarchy. They are not part of the API,
  1800.           and won't be present in Java systems from non-Sun vendors. Some
  1801.           people have reverse engineered the code and published an API for
  1802.           these classes but you use it at your own risk, and it may change
  1803.           without warning.
  1804.  
  1805.           Worst of all, those programs will not have the portability of true
  1806.           Java but will only run on Sun JDKs. For the same reason you
  1807.           shouldn't use classes outside the java.* packages when using JDKs
  1808.           from other vendors.
  1809.  
  1810.           If you still insist on going ahead, check these URLs:
  1811.           http://java.sun.com/products/api-overview/index.html
  1812.           http://www.parmly.luc.edu/javaudio/
  1813.           http://www.users.interport.net/~mash/javamidi.html
  1814.      5.7 How do you read environment variables from with a Java program?
  1815.  
  1816.      A. Environment variables are not used in Java, as they are not platform
  1817.      portable. The Mac doesn't have environment variables for example. Use
  1818.      properties instead. Additionally, on some systems you can set a
  1819.      property from the command invocation line like this:
  1820.           java -Dfoo=$foo MyClass (Unix)
  1821.      or
  1822.           java -Dfoo=%foo% MyClass (MS-DOS)
  1823.      This sets the "foo" property to the value of the environment variable
  1824.      foo. Make sure you do not leave any spaces after the -D or around the =
  1825.      sign. Inside the program you get the value with:
  1826.  
  1827.           String env = System.getProperty("foo");
  1828.  
  1829.      More simply, just put the environment variable on the commandline
  1830.      and read it as arg[0]
  1831.           java MyClass %FOO% ; Win32
  1832.           java MyClass $FOO ; Unix
  1833.      5.8 How do you use the Date class to display the current time in my
  1834.      timezone? Date.toString() always uses PST. [jdk 1.1] (Pacific Standard
  1835.      Time -- the zone covering California where JavaSoft is).
  1836.           A. To make things easier for debugging Sun has decided that the
  1837.           toString() method should always use one format, if you want a
  1838.           different format you should use the new internationalization
  1839.           routines.
  1840.  
  1841.           As a Date is stored internally in GMT the obvious choice for a
  1842.           standard format is... PST time? Taligent (who wrote this junk) is
  1843.           in the PST zone. As an example of how the new method should work
  1844.           jdk1.1/src/java/util/Date.java contains the method:
  1845.  
  1846.                DateFormat formatter = new SimpleDateFormat (
  1847.                           "d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
  1848.  
  1849.                formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
  1850.  
  1851.           or even:
  1852.  
  1853.                formatter.setTimeZone(TimeZone.getDefault());
  1854.  
  1855.           It should be reasonably straight forward to adapt this code for
  1856.           your preferred format (e.g. change string to "hh:mm" or other) and
  1857.           timezone, e.g. change "GMT" to "ECT", "JST" or other timezone.
  1858.  
  1859.           Don't forget this code too, to prevent GMT being interpreted as
  1860.           GMT+1:00 hour.
  1861.  
  1862.                // + 1 is to work around bug in GregorianCalendar
  1863.                // XXX - need FIX
  1864.                // should probably be formatter.format( this );
  1865.                // or formatter.format(new Date());
  1866.  
  1867.                return formatter.format( new Date(getTime() + 1) );
  1868.  
  1869.      5.9 How are dates represented in Java?
  1870.           A. java.util.Date stores dates as long integers representing the
  1871.           number of milliseconds since 00:00:00 UTC Jan 1, 1970 (the birth
  1872.           of Unix, a date known as the "Epoch"). This is sufficient to
  1873.           represent dates from roughly 146,026,873 B.C. to 146,030,814 A.D.
  1874.           Dates earlier than the Epoch are represented as negative numbers,
  1875.           counting away from 1/1/1970.
  1876.  
  1877.           In JDK 1.1, Date was augmented by Calendar. Things didn't get any
  1878.           better. Instead of being ill-conceived and simple, it is now
  1879.           ill-conceived and complicated. The code was all licensed from
  1880.           Taligent. It didn't really improve matters. Dates are the lemon of
  1881.           Java, as Roedy Green truly notes.
  1882.      5.10 That may be, but how do I extract day, month, year from a Date?
  1883.           A. In JDK 1.1, Date represents an instant in time. Calendar
  1884.           translates between an instant in time, and individual fields like
  1885.           year, month, day, etc
  1886.  
  1887.           So get your Date -- the current Date can be had by
  1888.  
  1889.                Date now = new Date();
  1890.  
  1891.           Then construct a Calendar to do the translation:
  1892.  
  1893.                Calendar mycal = Calendar.getInstance();
  1894.                mycal.setTime(now);
  1895.  
  1896.           // Now read the Calendar's fields using get().
  1897.  
  1898.                System.out.println("Year = " + mycal.get(Calendar.YEAR));
  1899.  
  1900.           We hope all this junk will be fixed once and for all in a future
  1901.           release.
  1902.  
  1903.           The Calendar, DateFormat, and even TimeZone classes will give you
  1904.           the timezone of your system (wherever you are). The default time
  1905.           zone for SimpleDateFormats is PST (i.e. California).
  1906.      5.11 What kind of different date formats are allowed for the Date
  1907.      constructor with the string parameter.
  1908.           A. The Language Specification (which also covers the java.lang,
  1909.           java.util, and java.io packages) is the best reference for
  1910.           answering questions like this. It has much more detail than the
  1911.           API Documentation has, and it is available as a book or online at
  1912.                http://java.sun.com/docs/books/jls/html/javautil.doc.html
  1913.           The Date(String) constructor is deprecated in Java 1.1, by the
  1914.           way.
  1915.      5.12 How do I get Java talking to a Microsoft Access database?
  1916.           A. Use the JDBC-ODBC bridge. It is not especially challenging to
  1917.           set up, but it does require painstaking attention to detail. There
  1918.           is a step-by-step example in the van der Linden text "Just Java
  1919.           2nd Ed." mentioned in the sponsorship section of this document.
  1920.  
  1921.           Note that the Microsoft version of the Java kit does not support
  1922.           JDBC-ODBC access because it uses a non-standard native code
  1923.           interface. Also check the JDBC FAQ listed at the end of this
  1924.           document.
  1925.      5.13 I can't seem to change the current working directory.
  1926.           A. Correct. This missing functionality is an oversight that we
  1927.           hope will be corrected in future. Changing the user.dir property
  1928.           merely changes the text property, not the underlying reality that
  1929.           it is supposed to reflect.
  1930.      5.14 How do I create a Vector of ints?
  1931.           A. ints are primitive types and hence can't be stored by the
  1932.           Vector class which stores objects. You'll need to wrap the ints.
  1933.           Try this:
  1934.  
  1935.                int i =7;
  1936.                Vector holdsInts = new Vector(5,1);
  1937.  
  1938.                holdsInts.addElement(new Integer(i));
  1939.                int j = ((Integer)holdsInts.elementAt(0)).intValue();
  1940.  
  1941.      5.15 I have several worker threads. I want my main thread to wait for
  1942.      any of them to complete, and take action as soon as any of them
  1943.      completes. I don't know which will complete soonest, so I can't just
  1944.      call Thread.join on that one. How do I do it?
  1945.           A. You need to use the wait/notify mechanism to allow any of the
  1946.           worker threads to wake up your main thread when the worker has
  1947.           completed.
  1948.      5.16 How do I get random numbers?
  1949.           A. If you just need a quick random double between 0.0 and just
  1950.           less than 1.0
  1951.  
  1952.                double myrandom = Math.random(); // [0,1)
  1953.  
  1954.           The notation "[0,1)" is common math notation for "zero to .9999999
  1955.           etc" The Sun documents say this returns 0.0 to 1.0, but inspection
  1956.           of the source shows they are wrong. However, due to the inherent
  1957.           inaccuracies of floating point arithmetic, multiplying N by
  1958.           0.999999 etc can result in an answer of N, not N * .999999 . So
  1959.           watch out when N is big.
  1960.  
  1961.           Where things get even trickier is in the case where you want an
  1962.           int within a certain range, say 1 to 6 to simulate the throw of a
  1963.           die or 1 to 52 to represent a playing card. Class Random has a
  1964.           nextInt method that will return any integer:
  1965.  
  1966.                Random r = new Random();
  1967.                int i = r.nextInt();
  1968.  
  1969.           However, that has an (almost) 50% chance of being negative, and it
  1970.           doesn't come from the right range. So you just take the abs()
  1971.           value and then mod it into the right range:
  1972.  
  1973.                int dice_throw = 1 + Math.abs(i) % 6;
  1974.  
  1975.           Except, the abs() method fails gracefully in the presence of the
  1976.           Integer.MIN_VALUE (it returns the same, negative, result!). So it
  1977.           is better to AND to get the non-negative value: In general, to get
  1978.           a random int between high and low limits (incl.):
  1979.  
  1980.                Random r = new Random();
  1981.                int j = (Integer.MAX_VALUE & r.nextInt()) % (high-low+1) + low;
  1982.  
  1983.           The sentence states "(almost) 50% chance" because there is one
  1984.           more value in the negative integers than in the positive integers
  1985.           in two's complement arithmetic as used by Java. For most purposes,
  1986.           the bias introduced will be insignificant.
  1987.  
  1988.           A worse problem is that with the algorithm used, the low order
  1989.           bits are significantly less random than the higher order bits. And
  1990.           the low order bits are precisely the ones you get when you do the
  1991.           remainder operation.
  1992.  
  1993.      5.17 What does "deprecated" mean? I got this in a compiler error
  1994.      message.
  1995.           A. The compiler will flag a now-obsolete API as "deprecated". The
  1996.           word means "officially disapproved of". Compile again with the
  1997.           "-deprecation" option to see what is deprecated. In almost all
  1998.           cases, the old API has been replaced by a new one. Update your
  1999.           code to use the new one.
  2000.  
  2001.           An example of using a deprecated API is calling component.size().
  2002.           That has been replaced by component.getSize().
  2003.      5.18 Where/why should I use the Enumeration interface?
  2004.           A. It's a very convenient way to step through some of the library
  2005.           data structures, such as HashTable, Vector, and ZipFile. It is
  2006.           thread safe. If you're looking at an element in one thread while
  2007.           another thread is trying to delete it, it won't half vanish.
  2008.  
  2009.           Here's how you might look at every file in ZIP file:
  2010.  
  2011.                ZipFile z = new ZipFile("foo.zip");
  2012.                for (Enumeration e=z.entries(); e.hasMoreElements(); ) {
  2013.                    ZipEntry ze = (ZipEntry)e.nextElement();
  2014.  
  2015.                System.out.println("got " + ze.getName() );
  2016.                }
  2017.  
  2018.           You should look for opportunities in your own data structures to
  2019.           implement Enumeration, anywhere where the structure has repeated
  2020.           elements.
  2021.      5.19  Which version of WinZip is compatible with java.util.zip?
  2022.           A. You need WinZip version 6.2 or later. Version 6.1 or earlier is
  2023.           not good enough. WinZip can be downloaded from
  2024.           http://www.winzip.com/download.cgi. The pkzip software works fine.
  2025.  
  2026.                              -------------------
  2027.  
  2028. 6. I/O
  2029.  
  2030.      6.1 How do I read a String/int/boolean/etc from the keyboard?
  2031.           A. The easiest way is to pick up the source for the 100% pure Java
  2032.           class EasyIn from http://www.best.com/~pvdl (same place as this
  2033.           FAQ) Compile it with your code and use it like this:
  2034.  
  2035.                EasyIn easy = new EasyIn();
  2036.  
  2037.                int i = easy.readInt(); // gets an int from System.in
  2038.                boolean b = easy.readBoolean(); // gets a boolean from System.in
  2039.                double d = easy.readDouble(); // gets a double from System.in
  2040.  
  2041.           ... etc.
  2042.  
  2043.           EasyIn is free, comes with source, and you can do what you like
  2044.           with it, including improve it, and send me back the results.
  2045.  
  2046.           If, instead, you want to "roll your own" code (why?!) In JDK 1.0.2
  2047.  
  2048.                java.io.DataInputStream in = new java.io.DataInputStream(System.in);
  2049.                String s = in.readLine();
  2050.  
  2051.           One way in JDK 1.1
  2052.  
  2053.                java.io.BufferedReader in =
  2054.                       new java.io.BufferedReader( new InputStreamReader(System.in));
  2055.  
  2056.                String s = in.readLine();
  2057.  
  2058.           Once you have the token in a String, it is easy to parse it into
  2059.           one of the other types, as shown earlier in the FAQ. Yes, it is
  2060.           bone-headed, as it makes the simplest case of keyboard I/O
  2061.           unnecessarily complicated.
  2062.      6.2 Why do I have trouble with System.out.println()?
  2063.           A. Check the spelling. The last two characters are the letters
  2064.           "ell enn" not "one enn".
  2065.  
  2066.           The name of the method stands for "print line", since it prints a
  2067.           String and goes to the next line, rather than staying on the same
  2068.           line as System.out.print() does. Yes, the name is yet another Java
  2069.           naming inconsistency, since the input equivalent is readLine(),
  2070.           not readln().
  2071.      6.3 How do I write to the serial port on my PC using Java?
  2072.           A. If the port exists as a pathname in the filesystem, you can
  2073.           open it as a file and read/write. You can also print text this way
  2074.           by writing to "prn" or "lpt1" on a pc, and "/dev/something" on
  2075.           Unix.
  2076.           Writing a formfeed at the end of the file is essential on
  2077.           Windows95.
  2078.  
  2079. //class that opens the printer as a file and writes "Hello World" to it
  2080. import java.io.*;
  2081. public class lpt
  2082. {
  2083.         public static void main (String[] argv) {
  2084.                 try {
  2085.                         FileOutputStream os = new FileOutputStream("LPT1");
  2086.                                     //wrap stream in "friendly" PrintStream
  2087.                         PrintStream ps = new PrintStream(os);
  2088.  
  2089.                                     //print text here
  2090.                         ps.println("Hello world!");
  2091.  
  2092.                                     //form feed -- this is important
  2093.                                     //Without the form feed, the text
  2094.                                     //will simply sit in the print
  2095.                                     //buffer until something else
  2096.                                     //gets printed.
  2097.                         ps.print("\f");
  2098.                                     //flush buffer and close
  2099.                         ps.close();
  2100.                 }
  2101.                 catch (Exception e) {
  2102.                         System.out.println("Exception occurred: " + e);
  2103.                 }
  2104.         }
  2105. }
  2106.  
  2107.           The bigger problem is if you wish to change the characteristics of
  2108.           the port (e.g. baud rate, parity, etc). Java currently offers no
  2109.           portable way to do this. You will need to use a native method, or
  2110.           execute a system command. At least two companies have written a
  2111.           library to drive the port. See
  2112.                http://www.sc-systems.com has a library for Windows95,
  2113.                WindowsNT, OS/2, Mac PPC, Solaris Sparc, Linux x86, FreeBSD
  2114.                x86, HP/UX PA-RISC, and possibly others too.
  2115.                http://www.cd.com/portio
  2116.           In addition, there is a Unix serial port utility available with
  2117.           source at:
  2118.      http://www.blackdown.org/java-linux/downloads/Private/jarvi/rxtx-1.1.1p2.tar.gz
  2119.  
  2120.      6.4 How do I append to a file?
  2121.           A. There are two ways. JDK 1.1 introduced new constructors for two
  2122.           of the output classes, that allowed you to set a boolean flag:
  2123.  
  2124.                public FileWriter(String fileName, boolean append) throws IOException
  2125.                public FileOutputStream(String name, boolean append) throws IOException
  2126.  
  2127.           Another way is to do this:
  2128.  
  2129.                RandomAccessFile fd = new RandomAccessFile(file,"rw");
  2130.                fd.seek(fd.length());
  2131.  
  2132.           Then write using fd. Note that the latter method does not take
  2133.           advantage of the "append" mode present in many operating systems
  2134.           (such as all unixes). Such a difference may make a difference with
  2135.           multiple processes or threads appending to the same output file.
  2136.           This can happen frequently, even if not intended by the
  2137.           programmer, e.g. with logfiles in multitasking environments. With
  2138.           the lack of file-locking mechanisms in Java the issue becomes even
  2139.           more significant.
  2140.      6.5 Is it possible to lock a file using Java ?
  2141.           A. Java does not feature an API to lock a file or regions within a
  2142.           file. Code that needs to do this must take one of three
  2143.           approaches:
  2144.                1. implement an advisory locking scheme using features that
  2145.                Java does have (synchronized methods). This allows you to
  2146.                lock files against use by other Java code running in the same
  2147.                JVM.
  2148.  
  2149.  
  2150.                2. Use an atomic operation like "file delete" and have all
  2151.                processes (Java and non-Java) follow the same protocol: if
  2152.                the file was deleted by you, you have the lock, and you
  2153.                create the file again to give up the lock.
  2154.  
  2155.  
  2156.                3. make calls to native code to issue the locking ioctls.
  2157.                This approach is not portable, but gives you a shot at having
  2158.                your locks respected by other programs using standard locking
  2159.                ioctls outside Java.
  2160.      6.6 How do I make the keyboard beep in Java?
  2161.           A. In JDK 1.1, java.awt.Toolkit has the method beep(). It does not
  2162.           work on NT 4.0 (bug).
  2163.  
  2164.                System.out.print("\07");
  2165.                System.out.flush();
  2166.  
  2167.           should work, and works in JDK 1.0.2, too. That's the ASCII BEL
  2168.           character (Java doesn't support the C abstraction of '\a' for an
  2169.           alert character).
  2170.      6.7 How do I execute a command from Java? How do I do I/O redirection
  2171.      in Java using exec() ?
  2172.           A. See answer to question 10.5
  2173.      6.8 How do you do file I/O from an applet?
  2174.           A. For security reasons, untrusted applets accessed across the
  2175.           network are restricted from doing certain operations, including
  2176.           I/O. This prevents rogue applets from sending out your private
  2177.           data, or deleting it. A trusted (signed) applet can perform these
  2178.           operations (JDK 1.1 on).
  2179.  
  2180.           The following suggestion is for server-side input.
  2181.  
  2182.           - You can read a file on the server if you can create a URL
  2183.           referencing the file. Then open a stream, then use any of the
  2184.           stream-based methods to read.
  2185.  
  2186.           This allows reading but not writing. It requires an http demon
  2187.           running on the server, which will usually be the case.
  2188.  
  2189.                try{
  2190.                   URL url = new URL("http://somewhere.com/test.txt");
  2191.                   // or URL url = new URL( getDocumentBase(), filename);
  2192.                   DataInputStream dis = new DataInputStream(url.openStream());
  2193.                   String s = dis.readLine(); //read till you get a null line.
  2194.                } catch(MalformedURLException e){System.out.println("URLException:"+e);}
  2195.                catch(IOException e){System.out.println("IOException:"+e);}
  2196.  
  2197.           You cannot write a file on the server this way.
  2198.  
  2199.           The following suggestions are for server-side output.
  2200.  
  2201.           It absolutely requires the cooperation of the server to allow an
  2202.           applet to write a file to the server. This cooperation may take
  2203.           any of several forms:
  2204.              + ftp server process
  2205.              + file server (custom written)
  2206.              + listening on a socket for data from applets
  2207.              + CGI script
  2208.              + Java RMI (remote method invocation)
  2209.           In particular:
  2210.                1. Or open a socket back to the server and read/write the
  2211.                data. Have a process on the server that listens for socket
  2212.                connections from applets and does the requisite I/O. This
  2213.                does I/O on the server.
  2214.  
  2215.                2. Or use a CGI script or servlet on the server to write when
  2216.                browsed. There is some source at
  2217.                ftp://ftp.oyster.co.uk/pub/java/fileIO/
  2218.  
  2219.                The following suggestions are for client-side I/O.
  2220.  
  2221.                3. Use a trusted applet (see section on security). This will
  2222.                permit local I/O without any of the restraints mentioned
  2223.                above. In this regard, the appletviewer and many other
  2224.                browsers regard applets loaded from a local filesystem
  2225.                (rather than across the net) as being more trustworthy, and
  2226.                perhaps even allowed to do I/O.
  2227.  
  2228.                4. Or use a browser that has a security policy that is
  2229.                configured to allow file I/O (such as Sun's appletviewer).
  2230.  
  2231.                Also see the answer to question 5.2 regarding the JENI
  2232.                library.
  2233.      6.9 I used a C program to write a binary file. When I instatiate a
  2234.      DataInputStream on the file in Java, and try to readInt, I do not get
  2235.      the correct numbers. Why is this?
  2236.           A. Java does everything in network byte order (big-endian order),
  2237.           as do many computers including Motorola, and SPARC. The Intel x86
  2238.           uses little endian order in which the 4 bytes of an int are stored
  2239.           least significant first. Rearranging the bytes on the way in will
  2240.           get you the results you need. This is only necessary when the file
  2241.           was written by a non-Java program on a little endian machine such
  2242.           as a PC.
  2243.  
  2244.           The following code will byte-swap little-endian integers into
  2245.           network standard order
  2246.  
  2247.                public int swap(int i) {
  2248.                    int byte0 = i & 0xff;
  2249.                    int byte1 = (i>>8) & 0xff;
  2250.                    int byte2 = (i>>16) & 0xff;
  2251.                    int byte3 = (i>>24) & 0xff;
  2252.                    // swap the byte order
  2253.                    return (byte0<<24) | (byte1<<16) | (byte2<<8) | byte3;
  2254.                }
  2255.  
  2256.      6.10 How do I make I/O faster? My file copy program is slow.
  2257.           A. This is the purpose of BufferedInputStream. It is a flaw in
  2258.           Java that buffered I/O is not the default, with a flag or
  2259.           different constructor to turn it off. I/O is the second worst
  2260.           designed package in Java, after the Date class.
  2261.      6.11 How do I do formatted I/O of floating point numbers?
  2262.           A. Look at http://www.apl.jhu.edu/~hall/java/CoreJava-Format.html
  2263.           for the html with the javadoc info. The actual file is called
  2264.           http://www.apl.jhu.edu/~hall/java/CoreJava-Format.java However,
  2265.           you must rename the file to Format.java for it to compile.
  2266.  
  2267.           Although many utilities claim to handle all varieties of C's
  2268.           printf, as far as has been found, this is the only one to
  2269.           correctly handle the equivalent of %e in printf.
  2270.      6.12 How do I read numbers in exponential format in Java?
  2271.           A: The program below (written by Steve Chapel) uses
  2272.           StreamTokenizer to read data from the standard input and
  2273.           recognizes doubles in exponential format (e.g. -1.23e-45).
  2274.  
  2275.                import java.io.*;
  2276.  
  2277.                public class ReadExponential {
  2278.                    public static void main(String argv[]) {
  2279.                        DataInputStream in = new DataInputStream(System.in);
  2280.                        StreamTokenizer st = new StreamTokenizer(in);
  2281.                        try {
  2282.                            while (st.nextToken() != StreamTokenizer.TT_EOF) {
  2283.                                switch (st.ttype) {
  2284.                                case StreamTokenizer.TT_NUMBER:
  2285.                                    double num = st.nval;
  2286.                                    int exp = 0;
  2287.                                    st.ordinaryChars('\0', ' ');
  2288.                                    st.nextToken();
  2289.                                    st.whitespaceChars('\0', ' ');
  2290.                                    if (st.ttype == StreamTokenizer.TT_WORD &&
  2291.                                        Character.toUpperCase(st.sval.charAt(0)) == 'E') {
  2292.                                        try {
  2293.                                            exp = Integer.parseInt(st.sval.substring(1));
  2294.                                        } catch (NumberFormatException e) {
  2295.                                            st.pushBack();
  2296.                                        }
  2297.                                    } else if (st.ttype < 0 || st.ttype > ' ')
  2298.                                        st.pushBack();
  2299.                                    System.out.println("Num  " + num * Math.pow(10, exp));
  2300.                                    break;
  2301.                                case StreamTokenizer.TT_WORD:
  2302.                                    System.out.println("Word " + st.sval);
  2303.                                    break;
  2304.                                default:
  2305.                                    System.out.println("Char '" + (char) st.ttype + "'");
  2306.                                    break;
  2307.                                }
  2308.                            }
  2309.                        } catch (IOException e) {
  2310.                            System.out.println("IOException: " + e);
  2311.                        }
  2312.                    }
  2313.                }
  2314.  
  2315.      6.13 I'm trying to read in a character from a text file using the
  2316.      DataInputStream's readChar() method. However, when I print it out, I
  2317.      get ?'s.
  2318.           A. Remember that Java characters are 16-bit Unicode characters,
  2319.           while many hosts systems store characters as 8-bit ASCII
  2320.           characters. Therefore, to read individual chacters from a text
  2321.           file, you need to ensure the proper conversion. The proper way to
  2322.           do this is to use an InputStreamReader, which converts from 8 to
  2323.           16 bit streams:
  2324.  
  2325.                FileInputStream fis = new FileInputStream("myfile.txt");
  2326.                InputStreamReader isr = new InputStreamReader(fis);
  2327.                char c3 = (char) isr.read();
  2328.  
  2329.           The less-favored way (because it is not so portable, as the
  2330.           encodings translation is not done) is just to read a byte and cast
  2331.           it into a character:
  2332.  
  2333.                FileInputStream fis = new FileInputStream("myfile.txt");
  2334.                DataInputStream dis = new DataInputStream(fis);
  2335.                char c1 = (char) dis.readByte();
  2336.  
  2337.      6.14 How do I delete a directory in Java?
  2338.           A. JDK 1.0 did not support directory removal. JDK 1.1 supports
  2339.           directory removal with the method:
  2340.                public boolean delete() in class java.io.File
  2341.           Make sure you don't have any open streams in the directory you're
  2342.           trying to remove. Do a close() on all streams, even if the
  2343.           underlying file is gone.
  2344.      6.15 How do I tell how much disk space is free in Java?
  2345.           A. There currently aren't any good Java APIs for system
  2346.           introspection. There is no Java way to control processes, or look
  2347.           at system resources. You have to Runtime.getRuntime.exec() to do
  2348.           "df" on unix or "dir" on Windows right now.
  2349.      6.16 What is the difference between the various ZIP formats: ZIP, GZIP,
  2350.      and PKZIP?
  2351.           A. GZIP files (the Gnu format) are not archives and compress only
  2352.           one file. GZIP is essentially a one file subset of the Zip format.
  2353.           Zip is an archive file format, popularized on PCs, that contains
  2354.           multiple compressed files. PKZIP is a set of
  2355.           commercially-available programs that create Zip files. All three
  2356.           PKZIP, GZIP and Zip use the deflate compression format, which is
  2357.           based on the LZ77 algorithm. This compression is also used by the
  2358.           zlib library and the PNG graphics file format. The format is
  2359.           specified in RFCs 1950, 1951, and 1952, and is unencumbered by
  2360.           licenses or patents.
  2361.  
  2362.           An alternative compression technology, LZW compression, is
  2363.           encumbered by Unisys's patent. LZW is used in GIF files and by the
  2364.           Unix compress command. Luckily, as well as being free from patent
  2365.           restrictions, LZ77 also gives better compression than LZW. LZW is
  2366.           the initial letters of the last names of the three computer
  2367.           scientists who developed the algorithm (Lempel, Ziv, Welch).
  2368.  
  2369.           The basic classes (all in java.util.zip) that read LZ77 Zip format
  2370.           are Deflater and Inflater. These are used by the stream classes
  2371.           DeflaterOutputStream and InflaterInputStream. The java.util.zip
  2372.           classes GZIPInputStream and ZipInputStream inherit from
  2373.           InflaterInputStream.
  2374.  
  2375.           PKZIP is a commercial program for DOS, Windows, and OS/2, sold by
  2376.           PKWARE Their FAQ (http://www.pkware.com/zipgfaq.html) specifically
  2377.           says
  2378.                "Because PKWARE has dedicated the .ZIP file format to the
  2379.                public domain, it is possible for other people to write
  2380.                programs which can read .ZIP files. NOTE THAT THE PKZIP,
  2381.                PKUNZIP, PKSFX PROGRAMS AND THEIR ASSOCIATED SOURCE CODE AND
  2382.                SUPPORT PROGRAMS ARE THE EXCLUSIVE PROPERTY OF PKWARE INC.
  2383.                AND ARE NOT PUBLIC DOMAIN SOFTWARE PROGRAMS.
  2384.           PKZIP's free (C language) source code was the basis for the JDK1.1
  2385.           Zip package AND the GNU GZIP program. The Zip classes' Javadocs
  2386.           acknowledge this.
  2387.  
  2388.           The "other people" PKZIP's FAQ refers to is the InfoZIP project, a
  2389.           bunch of hackers spread over the world producing free software
  2390.           that works on most ANSI C compilers and platforms. See
  2391.                http://www.cdrom.com/pub/infozip/
  2392.           Jar files are in PKZIP format, but are not as complete as a full
  2393.           filesystem archive format since file permissions are not saved.
  2394.           Some versions of WinZip are known to be inadequate for processing
  2395.           the full PKZIP format. Use infozip.
  2396.  
  2397.      6.17 How can I use characters other than ASCII in Java?
  2398.           A.Look for the article titled "Adding Fonts to the Java Runtime"
  2399.           at
  2400.           http://java.sun.com/products/jdk/1.1/docs/guide/intl/fontprop.html.
  2401.  
  2402.           This article explains how to add fonts to Sun's JDK, using the
  2403.           font.properties file. [If anyone has similar information for
  2404.           Netscape or IE, please send it in].
  2405.      6.18 I did a read from a Buffered stream, and I got fewer bytes than I
  2406.      specified, even though there are more bytes in the Stream.
  2407.           A. Correct. This is one of the "gotcha's" of buffered input. The
  2408.           system will try hard to buffer reads, even to the extent of
  2409.           sending you less data than you asked for. Nothing is lost of
  2410.           course, and you are always told how many bytes you actually got.
  2411.           You will get the remaining bytes on a subsequent read. This is
  2412.           also true with network operations (reads on sockets etc) and has
  2413.           always been true regardless of the language used. You really have
  2414.           to look at the "amount of data returned" field when using the
  2415.           read(byte[], int, int) method of BufferedInputStream.
  2416.      6.19 How do I get a directory listing of the root directory C:\ on a
  2417.      PC?
  2418.           A. The obvious approach of calling File.list("C:\"); does not
  2419.           work. There are two reasons why this fails. First, slash is an
  2420.           escape character in Java, so if you want a literal slash, you have
  2421.           to repeat it. Second, you need to give the name of the directory,
  2422.           i.e. dot. Putting this together, either of the following calls
  2423.           will work
  2424.  
  2425.           File.list("C:\\.");
  2426.           or
  2427.           File.list("C:/.");
  2428.  
  2429.                                 ------------------
  2430.  
  2431. 7. NETWORKING & DISTRIBUTED OBJECTS
  2432.  
  2433.      7.1 Should I use CORBA in preference to RMI? Or DCOM? Or what?
  2434.           A. If your distributed programs are all in Java, then RMI provides
  2435.           a simpler mechanism that allows the transfer of code,
  2436.           pass-by-value of real Java objects, and automatic garbage
  2437.           collection of remote objects.
  2438.  
  2439.           If you need to connect to C++ (or other language) systems or you
  2440.           need CORBA-specific services, then CORBA is your choice.
  2441.                http://www.javaworld.com/javaworld/jw-10-1997/jw-10-corbajava.html
  2442.           has a good intro to CORBA in the Java world.
  2443.  
  2444.           In July 1997, Sun announced that it was aligning RMI to work more
  2445.           closely with CORBA. Sun is simply adding an IIOP transport layer
  2446.           to RMI to support interoperability with CORBA. Java programs can
  2447.           then access CORBA-based objects through IIOP, the OMG's
  2448.           CORBA-based protocol. This is very good news for those building
  2449.           heterogenous Enterprise systems, although it will take some
  2450.           additions to IIOP to support the pieces that RMI uses.
  2451.  
  2452.           Microsoft spokespeople have tried to promote DCOM by spreading
  2453.           misinformation that RMI is changing or being dropped. That is
  2454.           totally wrong. The RMI API continues unchanged in its current
  2455.           form. Using DCOM would restrict your code to only ever run on
  2456.           Microsoft platforms using Intel hardware, and negates the "write
  2457.           once, run anywhere" Java philosophy. Non-portable, single vendor
  2458.           code should be avoided.
  2459.      7.2 Why does <my java debugger/IDE/other> hang for a couple of minutes
  2460.      if my Windows PC is not dialed up to the Internet?
  2461.           A. Java has networking support built in. When the Java program
  2462.           starts the Winsock dll automatically gets loaded. The first thing
  2463.           this does is to try to resolve the fully qualified domain name for
  2464.           your machine under the name "localhost". If your system doesn't
  2465.           have this name mapped, it will try to query a nameserver on the
  2466.           internet, which is typically (on a PC) your dialup ISP. So it
  2467.           either prompts you to connect to the ISP, or waits till the
  2468.           attempt times out.
  2469.  
  2470.           You can avoid the problem by giving your system another way to
  2471.           resolve DNS names. Edit the hosts file for your system (found in
  2472.           %windir%\hosts on Win95 and %windir%\system32\drivers\etc\hosts on
  2473.           NT) so that localhost and the full domain name are both mentioned.
  2474.           So if my system is called goober.best.com change the hosts file
  2475.           from
  2476.                127.0.0.1 localhost
  2477.           to
  2478.                127.0.0.1 goober.best.com localhost
  2479.           [If any networking gurus have improvements to this process,
  2480.           send'em in!]
  2481.  
  2482.           There is a longer, different procedure at
  2483.           http://www.best.com/~pvdl Please send me mail (pvdl@best.com) if
  2484.           either or both of these work or don't work for you, so I can
  2485.           update the FAQ.
  2486.  
  2487.      7.3 If I call the InetAddress.getByName() method with an
  2488.      IP-address-string argument, like "192.168.0.1", I get an
  2489.      UnknownHostException on some platforms, but not others. Code like
  2490.  
  2491.           Socket sock = new Socket("155.152.5.1", 23);
  2492.  
  2493.      triggers the exception. Why?
  2494.           A. This is a platform difference that arises out of different
  2495.           semantics in the underlying network libraries, and is [said to be,
  2496.           but subject to confirmation] fixed in JDK 1.1. On Solaris and
  2497.           Windows NT, the IP address string only works for IP addresses that
  2498.           have an associated hostname. On Linux and Windows 95, the IP
  2499.           address string works in all cases.
  2500.           http://www.cdt.luth.se/~peppar/java/InetAddress/ has a workaround.
  2501.  
  2502.           When InetAddress is instantiated with an IP address, a reverse DNS
  2503.           lookup is done. If the IP address is not associated with a valid
  2504.           hostname, the instantiation will fail. This is part of anti
  2505.           DNS-spoofing, and in JDK 1.1 works because the reverse lookup will
  2506.           not occur until the hostname is asked for. So in JDK 1.1,
  2507.  
  2508.                InetAddress in = InetAddress.getByName("155.152.5.1");
  2509.  
  2510.           should always work.
  2511.  
  2512.           [Note: this info is still to be confirmed. Net gurus?]
  2513.      7.4 I am using JDK 1.1.1 on Windows95, and when I start jdb I get
  2514.      "Uncaught exception: java.lang.UnsatisfiedLinkError no winawt in shared
  2515.      library path"
  2516.  
  2517.      The same program works OK using jdk1.1
  2518.           A. It *sounds* like your java\bin directory is not on your PATH
  2519.           and so the system can't find the winawt DLL.
  2520.  
  2521.           But actually the problem is the version of Microsoft's Visual C++
  2522.           that was used to build the product. VC++ 4.2 incorrectly generates
  2523.           code that depends on MSCVRT.DLL or in the case of java_g,
  2524.           MSVCRTD.DLL. These DLLs are not present in (some versions of)
  2525.           Win95. To make things even more interesting, some versions of
  2526.           Win95 (yes, there are at least four different ones...) ship with a
  2527.           broken MSVCRT.DLL (and MSVCRTD.DLL?) that seems to work, only it
  2528.           doesn't, and after a while it dies.
  2529.  
  2530.           Sun linked the winawt_g.dll with VC++ 4.2, which wrongly brought
  2531.           in MSVCRTD.DLL, the debug version of the VC++ runtime. You have to
  2532.           get that library from somewhere (like, say, VC++)
  2533.           in order to get jdb to run.
  2534.  
  2535.           You'll hit this problem any time you try to debug 1.1.1 code with
  2536.           jdb on a win95 system that doesn't have VC++ (or the MSVCRTD.DLL
  2537.           library from some other source) installed. At least this is a
  2538.           problem you can solve without waiting for the next release.
  2539.  
  2540.           Some people say that the missing library has been seen at
  2541.           http://cag-www.lcs.mit.edu/curl/Binaries/PC/ Others say you need
  2542.           to buy VC++ to get it.
  2543.  
  2544.      7.5 I want to pass a class file to willing recipients who are using my
  2545.      applet. Any ideas how?
  2546.           A. You could use a trick: put your .class file(s) in a .zip
  2547.           archive and use showDocument() on the URL. A person accessing this
  2548.           will get a dialog box put up asking them about saving the file to
  2549.           their local hard disk. You can see this in action and try it out
  2550.           yourself at:
  2551.                http://www.best.com/~rmlynch/saveit.html
  2552.  
  2553.      7.6 How do you succeed with new URL(someURL) from behind a proxy
  2554.      server?
  2555.           A. Tell the run time system what you are trying to do, like this:
  2556.                java -DproxySet=true -DproxyHost=proxy_host
  2557.                -DproxyPort=proxy_port \MyJavaProgram
  2558.           note proxyPort is optional and it defaults to 80.
  2559.  
  2560.      7.7 What is "swizzle", as in "Swizzle this object?"
  2561.           A. It means serialize. To swizzle an object is to recursively
  2562.           serialize or flatten composed objects.
  2563.  
  2564.      7.8 I have been using the Serializing capabilities in 1.1 to save some
  2565.      objects to disk. I added a new field to one of my objects that get
  2566.      serialized and now deserializing my old data no longer works. I get
  2567.      this exception:
  2568.  
  2569.           java.io.InvalidClassException: MacroData; Local class not compatible
  2570.  
  2571.           A. You need to add a declaration such as
  2572.  
  2573.                static final long serialVersionUID = 4021215565287364875L;
  2574.  
  2575.           in the modified class. The actual value of this long is supplied
  2576.           by the "serialver" utilitity suppied with the JDK. Any versions of
  2577.           a class other than the first version require this static to be
  2578.           defined
  2579.           in the class. This is how versioning is achieved.
  2580.      7.9 My socket code looks good, but is broken!
  2581.           A. When using sockets you typically open both inward and outward
  2582.           streams. If you close one of them, the other seems to 'break'
  2583.           instantly. Check whether this is happening for you, by adding the
  2584.           matched pair.
  2585.  
  2586.           [comments from net gurus welcome]
  2587.      7.10 How do I map between IP address and hostname?
  2588.           A. In Java 1.1 (earlier releases were buggy) use:
  2589.  
  2590.                String host = InetAddress.getByName("211.10.2.119").getHostName();
  2591.  
  2592.      7.11 How do I embed an anchor in a URL? Just putting it as part of the
  2593.      string in the constructor doesn't work.
  2594.           A. Like this:
  2595.  
  2596.                URL url = new URL("http://www.my_domain.com/my_page.html");
  2597.                URL anchor = new URL(url, "#section2");
  2598.                this.getAppletContext().showDocument(anchor);
  2599.  
  2600.      7.12 RMI seems to have stopped working for me in JDK 1.1. Why is this?
  2601.           A. The rules for where the client looks for a stub class seem to
  2602.           have changed making it necessary to reset your class path on the
  2603.           client after starting the rmi registry. In particular, it looks
  2604.           like rmic was not updated to the new "don't need $CLASSPATH"
  2605.           convention as the compiler was.
  2606.  
  2607.           There are several very good sources available from Sun which cover
  2608.           many simple and advanced RMI problems. They are:
  2609.              + The documentation, of course:
  2610.                     http://java.sun.com/products/jdk/1.1/docs/guide/rmi/index.html
  2611.              + Dedicated FAQs on RMI and Object Serialization
  2612.                     http://java.sun.com/products/jdk/rmi/faq.html
  2613.              + Mailing list RMI-USERS@JAVASOFT.COM with archive at
  2614.                     http://chatsubo.javasoft.com/email/rmi-users/
  2615.           Visit the archive!
  2616.      7.13 After a number of RMI client to server connections (55 on my
  2617.      system), subsequent RMI clients trying to connect fail. Why?
  2618.           A. You are hitting the default limit of 64 open file descriptors.
  2619.           Try increasing the limit in your OS.
  2620.  
  2621.           In addition there is currently a practical RMI connection limit
  2622.           imposed by the scalability of the VM and the performance of object
  2623.           serialization. In JDK 1.2 this is addressed. The actual number of
  2624.           active clients you will be able to support will depend on the
  2625.           workload mix you have (i.e. the number of clients, how often they
  2626.           talk to the server, and how much work must be done per call).
  2627.      7.14 How do I POST to a CGI script from an applet?
  2628.           A. For an untrusted applet, the CGI script can only be on the
  2629.           server that served the applet. Then use code like this:
  2630.  
  2631.                try { sock = new Socket(host, 80);
  2632.                dock = new DataOutputStream(sock.getOutputStream());
  2633.                dock.writeBytes("POST "+cgiloc+" HTTP/1.0\n");
  2634.                dock.writeBytes("Content-type: text/html\n");
  2635.                dock.writeBytes("Content-length: " +my_string.length() + "\n\n");
  2636.                dock.writeBytes(my_string+"\n");
  2637.                dock.close();
  2638.                sock.close();
  2639.  
  2640.                uresp = new URL(getDocumentBase(),"respond.html");
  2641.                getAppletContext().showDocument(uresp); }
  2642.  
  2643.           The my_string contains the data you want to POST to the CGI
  2644.           script. The string should be encoded in the special way CGI
  2645.           expects. The class method java.net.URLEncoder.encode(my_string)
  2646.           will do it.
  2647.  
  2648.           If you request a url via the URLConnection/HttpURLConnection, the
  2649.           server sets the content type, and your applet can use
  2650.           URLConnection.getContentType() to get the type. Alternatively, use
  2651.           setRequestProperty to set it, like this:
  2652.  
  2653.                url = new URL(cgiUrl);
  2654.                urlc = url.openConnection();
  2655.                urlc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
  2656.  
  2657.                                    -----------------
  2658.  
  2659. 8. MULTI-MEDIA
  2660.  
  2661.      8.1 Why won't my audio file play?
  2662.           A. Java 1.1 and earlier releases use one audio format exclusively.
  2663.           The audio file must be in .au format, recorded at 8 KHz, mono, in
  2664.           mu-law encoding. If your audio clip is in a different format
  2665.           (e.g., .wav) or a different frequency it must be converted to the
  2666.           exact specifications above before Java can play it. Support for
  2667.           .wav and other formats is part of the Java Media Framework coming
  2668.           in JDK 1.2.
  2669.  
  2670.           Search at www.yahoo.com for GoldWave for Win 95, sox for Unix and
  2671.           similar conversion utilities for other systems. One conversion
  2672.           utility in Java is at http://saturn.math.uaa.alaska.edu/~hursha
  2673.           The source of a Java class to play linear PCM .WAV files is at:
  2674.           http://www.shef.ac.uk/~cs1mjp/Java/WhiteBoard/WavePlayer.html It
  2675.           can be used in any Java application or applet.
  2676.      8.2 Does Java support Animated GIFs?
  2677.           A. Java 1.0.2 and earlier releases use GIF and JPEG formats, and
  2678.           do not use the GIF89 animated GIF format. (An animated GIF is one
  2679.           that contains successive frames of an image, so when they are
  2680.           displayed in quick sequence the image appears to contain
  2681.           movement). When you display an animated GIF in Java 1.0.2, you
  2682.           will just get the first frame. There doesn't appear to be any easy
  2683.           way to get other frames from the image.
  2684.  
  2685.           The advantage of an animated GIF file is that there is only one
  2686.           file to download, and it is simple to do simple animations. The
  2687.           advantage of programmatic control over individual frames is that
  2688.           you control the rate and order of displaying them.
  2689.  
  2690.           Here's a surprise: JDK 1.1 supports the animated display of
  2691.           animated GIFs. For simple animations animated GIFs are a lot
  2692.           easier and lighter-weight than coding an animation explicitly.
  2693.  
  2694.           8.2.0  How do I create animated GIFs?
  2695.                A. Use GIFanimator from ULead (said to be the best)
  2696.                http://www.ulead.com, or GIF Construction Set from Alchemy
  2697.                Mindworks
  2698.  
  2699.           8.2.1 How do I prevent animated GIFs from flashing while
  2700.           displaying?
  2701.                A. The problem is most likely that in your paint method you
  2702.                have
  2703.  
  2704.                     g.drawImage(img, ix, iy, this);
  2705.  
  2706.                You should change this to
  2707.  
  2708.                     g.drawImage(img, ix, iy, getBackground(), this);
  2709.  
  2710.                This will change all the transparent regions of the image to
  2711.                the background color before painting to the screen. If you
  2712.                paint transparent images directly to the screen they flicker.
  2713.  
  2714.                If that does not solve it then check that:
  2715.                     1. ImageUpdate is
  2716.  
  2717.                     public boolean imageUpdate(Image img, int flags, int x,
  2718.                                                int y, int width, int height) {
  2719.                         if ((flags & (FRAMEBITS|ALLBITS))!= 0) {
  2720.                            repaint();
  2721.                         }
  2722.  
  2723.                         return (flags & (ALLBITS|ABORT)) == 0;
  2724.                     }
  2725.  
  2726.                     2. update is
  2727.  
  2728.                     public void update(Graphics g) {
  2729.                         paint(g);
  2730.                     }
  2731.  
  2732.                If you have a background Image behind the partly transparent
  2733.                animated GIF you will have to double buffer. You can crop the
  2734.                backgound image so you won't have to double buffer the full
  2735.                app and waste too much memory.
  2736.      8.3 Does Java support transparent GIFs?
  2737.           A. GIF89a images with a transparent background show up as
  2738.           transparent without further filtering. This has been supported
  2739.           from 1.0 on. Java correctly displays both animated GIFs and
  2740.           transparent GIFs.
  2741.  
  2742.           Even better, you can fill the transparent pixels with a color (so
  2743.           they appear non-transparent in Java). Just pass the fill color
  2744.           explicitly:
  2745.  
  2746.                drawImage(img, x, y, w, h, fillcolor, this);
  2747.  
  2748.           Further, you can filter the pixels of an Image to turn any bits
  2749.           you wish transparent. However, the most you can do is reveal what
  2750.           is underneath the image. You cannot reveal what is underneath the
  2751.           applet (i.e. on the browser itself). By default applets have a
  2752.           plain grey background.
  2753.      8.4 How do I play video in Java?
  2754.           A. Use the Java Media Framework Player API
  2755.  
  2756.           The spec can be found at
  2757.                http://java.sun.com/products/java-media/jmf/mediaplayer/
  2758.           Intel has released a SDK for the Java Media Framework Player API.
  2759.           The SDK is for Windows 95 and Windows NT For more information, see
  2760.                http://developer.intel.com/ial/jmedia
  2761.           SGI has released an implementation of JMF for IRIX:
  2762.                See http://www.sgi.com/Products/motion/
  2763.      8.5 How can I play *.au files from an application?
  2764.           A. You've got 2 options:
  2765.                a. Use the AudioClip or AudioPlayer class in sun.audio
  2766.                     http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
  2767.                If you take this option, you can only play AU files. Worse,
  2768.                your code is no longer 100% pure Java, as it relies on a
  2769.                vendor library.
  2770.  
  2771.                     import sun.audio.*;
  2772.  
  2773.                     URL url; ...
  2774.                     AudioStream audiostream = new AudioStream(url.openStream());
  2775.                     AudioPlayer.player.start(audiostream);
  2776.                     ...
  2777.                     AudioPlayer.player.stop(audiostream);
  2778.  
  2779.                b. Use the new Java Media Framework API, allowing a wide
  2780.                range of video and audio formats to be played back. See
  2781.                previous question for implementations of this.
  2782.      8.6 How do I read in an image file, in an application?
  2783.           A. Use
  2784.  
  2785.                Image img = Toolkit.getDefaultToolkit().getImage(fname);
  2786.  
  2787.      8.7 When I initialize a component, I call MyComponent.getImage() to get
  2788.      its image. createImage() returns null! I know the image works
  2789.      elsewhere. What's wrong?
  2790.           A. A peer component needs to exist for your component before you
  2791.           can get its image. This is done by the method addNotify() (surely
  2792.           one of the most poorly named methods in all Java -- it doesn't
  2793.           mean "add a Notify". It means "Notify that the Component has been
  2794.           added to a Container". This tells the system, "whoops, I'd better
  2795.           create the peer for this Component right away). addNotify will be
  2796.           called for you when you add your component to a container.
  2797.  
  2798.           If you override addNotify(), don't forget to call
  2799.           super.addNotify() in your overriding version.
  2800.      8.8 How can I force a reload a fresh version of an image into my
  2801.      applet? My image file is changed periodically, and I want the applet to
  2802.      go and retrieve it, not cache it.
  2803.           A. You need to turn off caching for the URL.
  2804.  
  2805.                URL url = null;
  2806.                URLConnection con;
  2807.                try {
  2808.                    url = new URL(getDocumentBase(),"image.jpg");
  2809.                    con = url.openConnection();
  2810.                    con.setUseCaches(false);
  2811.                } catch (MalformedURLException e1) {System.err.println(e1.getMessage());}
  2812.                catch (IOException e2) {System.er.println(e2.getMessage());}
  2813.  
  2814.           Note: some programmers have reported that it caches anyway, even
  2815.           if that do this. That is a browser bug.
  2816.  
  2817.           One programmer reported that even after turning off caching and
  2818.           calling image.flush() before getImage(..), he was still seeing the
  2819.           same picture even though it had been changed on the server.
  2820.  
  2821.           He worked out a solution: access the image via a cgi script that
  2822.           returned a URL. This redirects the browser, and he put in an
  2823.           Expires: header as well to force the reload. Painful and
  2824.           laborious, but it got the result.
  2825.      8.9 How can I save an Image file to disk in jpg or gif format?
  2826.           A. A number of people have written utilities to do that. One of
  2827.           them is available at the same place as this FAQ:
  2828.                http://www.best.com/~pvdl
  2829.                Jef Poskanzer has written an abstract ImageEncoder class and
  2830.                implemented it for GIFs and PPMs. Those are at
  2831.                http://www.acme.com/java/software/
  2832.                Hong Shi wrote a PPM to JPEG convertor.
  2833.                http://www.ctr.columbia.edu/~hshi/report6880.htm
  2834.                Florian Raemy has written a program that encodes a JPEG then
  2835.                decodes it again. http://lcavwww.epfl.ch/demos/jpeg.html
  2836.      8.10 What causes this problem?
  2837.  
  2838.           $ appletviewer m.html
  2839.           Premature end of JPEG file
  2840.           sun.awt.image.ImageFormatException: JPEG datastream contains no image
  2841.           at sun.awt.image.JPEGImageDecoder.produceImage(JPEGImageDecoder.java:133)
  2842.           at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:215)
  2843.           at sun.awt.image.ImageFetcher.run(ImageFetcher.java:98)
  2844.  
  2845.           A. There's a known bug in early releases of the JDK which can
  2846.           cause the above failure when reading a JPEG across a slow
  2847.           connection. The failure only occurs if the JPEG contains a large
  2848.           application data block (APPn marker) --- the problem is that the
  2849.           JPEG decoder is trying to skip over the APPn and failing if not
  2850.           all of the APPn has been received yet. The quoted error message is
  2851.           only one of several possible complaints, but they all stem from
  2852.           the same root.
  2853.  
  2854.           Photoshop is the most common source of JPEGs containing oversize
  2855.           APPn blocks. In particular, if you allow Photoshop 4 to save a
  2856.           thumbnail (preview) in a JPEG, the thumbnail plumps up Photoshop's
  2857.           private APPn marker to several K, which is usually enough to cause
  2858.           this problem.
  2859.  
  2860.           There are several possible workarounds:
  2861.                1. Get a newer JDK --- this problem is said to be fixed in
  2862.                1.1. (If you are putting images up on the Web, this isn't
  2863.                much of a solution, because you can't assume visitors to your
  2864.                site have an up-to-date Java installation.)
  2865.  
  2866.                2. When making JPEGs for Web use from Photoshop, make sure
  2867.                you have turned off the "save thumbnails" preference. (This
  2868.                is a good idea quite aside from bug workarounds, because the
  2869.                thumbnail is just a waste of download time as far as a Web
  2870.                browser is
  2871.                concerned.) You might still have a problem if you've got
  2872.                verbose comments or lots of paths being saved into the file,
  2873.                but 99% of the time, getting rid of the thumbnail will make
  2874.                Photoshop's APPn small enough to not trigger the Java bug.
  2875.  
  2876.                3. Use a tool such as 'jpegtran' (from the Independent JPEG
  2877.                Group) to strip out the Photoshop APPn entirely without any
  2878.                loss of image quality. Recommended answer for the compulsive
  2879.                byte-trimmer.
  2880.  
  2881.                4. (Last resort) Load and resave the image in a different
  2882.                image editor that won't insert any APPn or other overhead
  2883.                data. This implies a JPEG generational loss, so I don't
  2884.                recommend it if you are picky about image quality.
  2885.  
  2886.                Any large overhead marker will cause the same problem; 4K of
  2887.                comment text, say, in a COM marker. So Photoshop is not the
  2888.                only source of tickling this bug.
  2889.      8.11 How can I convert between GIF and JPEG formats?
  2890.           A. In a word: don't.
  2891.  
  2892.           There's hardly any overlap between the set of images that JPEG
  2893.           works well on and the set that GIF works well on. Sometimes, with
  2894.           enough care, you can get an acceptable conversion ... but most of
  2895.           the time gif<->jpeg conversion will just turn your image to mush.
  2896.           Far better to pick the right format in the first place.
  2897.  
  2898.           For more info see the JPEG FAQ at
  2899.           http://www.faqs.org/faqs/jpeg-faq/
  2900.      8.12 If you have an InputStream (rather than a file) that contains an
  2901.      Image, how can you display it?
  2902.           A: Using this method, and some adroit shuffling.
  2903.                Toolkit.getImage(URL url)
  2904.           Create a thread that pretends to be an http server. Make it listen
  2905.           to some port (8888 for example) for incoming requests. When the
  2906.           thread gets a request, it should simply whisk up the appropriate
  2907.           http headers and follow it by the InputStream. Thus the component
  2908.           that has the input stream and wants to do the getImage(url) can
  2909.           now invoke:
  2910.  
  2911.           Toolkit.getImage("localhost:8888/")
  2912.  
  2913.           The thread will act as a stream-to-url adapter, and send back the
  2914.           data It saves you from having to read 200K of JPEG data before you
  2915.           can begin drawing anything.
  2916.      8.13 How can I record sounds in Java?
  2917.           A. The Java Media Framework coming in JDK 1.2 will support this.
  2918.           In the meantime, there is a package for Win95/NT available at
  2919.           http://www.scrawl.com/store/
  2920.  
  2921.           It supports 8, 16-bit, stereo, mono, 11025, 22050, 44100 Hz
  2922.           record/play, load/save .WAV files.
  2923.      8.14 Does Java have any built-in support for displaying HTML?
  2924.           A. The JDK doesn't currently have any support for rendering HTML.
  2925.           The Swing software that will appear in JDK 1.2 has an elementary
  2926.           (graphics, tables, text) HTML bean that is good enough for simple
  2927.           rendering (help files, email, etc). Other alternatives include:
  2928.              + JavaBrowser http://www.ii.uib.no/~alexey/jb/index.html Free
  2929.                source, free for use under GNU LGPL licence, HTML 2.0 (sort
  2930.                of).
  2931.              + ICE Browser - Java Bean Component
  2932.                http://www.bgnett.no/datatech/ICEBrowser/ Free binaries for
  2933.                use in free applications. Commercial licensing available
  2934.                including source - flat fee licence. Thin HTML client!
  2935.                Lightweight! HTML 3.2
  2936.              + HotJava HTML Component - Java Bean Component
  2937.                http://www.javasoft.com/products/hotjava/bean/index.html $195
  2938.                for private use binary licence. HTML 3.2
  2939.              + HTML browser (free source)
  2940.                http://barium.tn.tudelft.nl/people/gool/java/html/Html.html
  2941.              + Web Window Browser http://www.opencube.com/example_wwb.htm
  2942.                $139 - no sources.
  2943.              + jHelp ($20-650)
  2944.                http://w3.nai.net/~rvdi/jhelp/jhelp2/jhelp.html jHelp is a
  2945.                HTML browser component written in Java, HTML 2.0
  2946.  
  2947.                                    -----------------
  2948.  
  2949. 9. SECURITY
  2950.  
  2951.      9.1 What is a "trusted applet"?
  2952.           A. JDK 1.1 introduced the notion of a "trusted applet" which is
  2953.           one that has been cryptographically-signed to guarantee its origin
  2954.           and make it tamper resistant. Trusted applets can be granted more
  2955.           system access privileges than untrusted applets.
  2956.  
  2957.           You preconfigure your browser with a list of whose X.509
  2958.           certificate you trust, and then applets arrive with X.509's
  2959.           attesting to their keys. It's easier than it sounds.
  2960.      9.2 What is the story with Java and viruses? What is the blackwidow
  2961.      virus?
  2962.           A. Java was designed with security in mind. The security features
  2963.           make it very difficult, probably impossible, to attach a virus
  2964.           (self- copying code) to a Java applet. As far as is known, there
  2965.           has never been a Java virus.
  2966.  
  2967.           There has been mention of a "Java virus" called "BlackWidow" in
  2968.           the media (it was mentioned in Unigram in late 1996, and obliquely
  2969.           on the RISKS newsletter in February 1997). A request to the editor
  2970.           of Unigram for more information brought the answer that there was
  2971.           no more information, it was just a report of a rumor. As far as is
  2972.           known, this story exists *only* as rumors reported on by the
  2973.           press. There is no actual Java virus or blackwidow virus (there
  2974.           was a legitimate commercial product of that name, since renamed).
  2975.           If anyone has more concrete information about a virus that can
  2976.           attack a Java applet (again, this is thought to be impossible),
  2977.           please would they contact the FAQ maintainer with details.
  2978.      9.3 Why do I get the warning string at the bottom of popup
  2979.      windows "Unsigned Java Applet Window" in my applets?
  2980.           A. This is a security feature, to make certain that users can
  2981.           always tell that a window asking for their password and credit
  2982.           card details (or whatever) is from an applet. There should be no
  2983.           way for an untrusted applet to work around this message. See also
  2984.           the answer to 4.1.3.
  2985.      9.4 Where can I find crypto libraries for Java?
  2986.           A. Cryptographic libraries are not part of the Java release
  2987.           because US Government policy classifies strong cryptography under
  2988.           the same rules as munitions. Its export is regulated under the
  2989.           International Traffic in Arms Regulations. Many people regard this
  2990.           as a Kafka-esque (and futile) attempt to stem the use of
  2991.           cryptography inside the US.
  2992.  
  2993.           A comprehensive and free crypto library (called Cryptix) is at
  2994.                http://www.systemics.com/software
  2995.           Another crypto library for Java is at
  2996.                http://www.acme.com/java/software/Package-Acme.Crypto.html
  2997.           Blowfish, CRC16, CRC32, DES, DES3, IDEA, RC4, ROT13 (can they
  2998.           really call that "crypto"?), and more.
  2999.  
  3000.           One commercial Java encryption source (from Ireland) is
  3001.                http://www.baltimore.ie/jcrypto.htm
  3002.           A complete crypto API for Java (with HTML documentation) at:
  3003.                http://www.geocities.com/SiliconValley/Heights/8298
  3004.           The library provides comprehensive and complete range of crypto
  3005.           library and functions covering DES, 3DES, IDEA, Blowfish ...and
  3006.           RSA, DH, DSA and PGP access to Java programmers. The crypto
  3007.           functions are based on the C cryptlib, by Peter Gutmann. It would
  3008.           be illegal to export this under current US government rules, but
  3009.           the author of the code is outside the US, and not subject to US
  3010.           export regulations. Download it today before it becomes illegal.
  3011.  
  3012.           Also, early access to Sun's Java Cryptography Extension (JCE) is
  3013.           available for JDK 1.1 at:
  3014.                http://java.sun.com/products/jdk/1.1/jce
  3015.           (This may not be exported outside the USA and Canada).
  3016.  
  3017.           There's a Q&A archive at
  3018.                http://jeeves.javasoft.com/hypermail/java-security-archive/index.html
  3019.  
  3020.           An actual port of PGP v2.6.3i to Java is at
  3021.           http://tassun.math.nsc.ru
  3022.      9.5 How do I find out what these terms mean?
  3023.           A. Read Bruce Schneier's excellent book "Applied Cryptography 2nd
  3024.           Ed." for more info on what these terms mean. Read David Kahn's
  3025.           excellent (if exhaustive) book "The Codebreakers" for more info on
  3026.           the history and background of encryption.
  3027.      9.6 Where is Javasofts Security FAQ?
  3028.           A. Javasoft's security FAQs can be found at
  3029.           http://java.sun.com/docs/books/tutorial/applet/security/capabilities.html
  3030.  
  3031.           http://java.sun.com/sfaq/index.html
  3032.           See also
  3033.           http://java.sun.com/products/jdk/1.1/docs/guide/security/
  3034.                                 ------------------
  3035.  
  3036. 10. Java IDIOMS
  3037.  
  3038.      10.1  How do I convert a String to an int?
  3039.  
  3040.           A. There are several ways. The most straightforward is:
  3041.  
  3042.                int i = Integer.parseInt(<String>);
  3043.  
  3044.           or
  3045.  
  3046.                i = Integer.parseInt(<String>,<int radix>);
  3047.  
  3048.           Note: there are similar methods for Byte, Short, and Long.
  3049.  
  3050.                int i = Integer.valueOf(my_str).intValue();
  3051.  
  3052.           also works but involves the creation of an extra object. Note: use
  3053.           this for floating point values, as there are no parseDouble or
  3054.           parseFloat methods.
  3055.  
  3056.           float f = float.valueOf(my_str).floatValue();
  3057.  
  3058.      10.2 How do I convert an int to a string?
  3059.           A. String s = String.valueOf(i);
  3060.                or
  3061.  
  3062.                     String s = Integer.toString(i);
  3063.  
  3064.                or
  3065.  
  3066.                     String s = Integer.toString(i, radix);
  3067.  
  3068.                or
  3069.  
  3070.                     String s = "" + i; // briefer but may result in extra object allocation.
  3071.  
  3072.           Note: there are similar classes for Double, Float, Long, etc.
  3073.      10.3How do I print the hex value of an int?
  3074.           A. Another way is
  3075.  
  3076.                int i = 0xf1;
  3077.                System.out.println("i is hex " + Integer.toHexString(i) );
  3078.  
  3079.      10.4 How can you send a function pointer as an argument?
  3080.           A. Simple answer: use a "callback". Make the parameter an
  3081.           interface and pass an argument instance that implements that
  3082.           interface.
  3083.  
  3084.                public interface CallShow { public void Show( ); }
  3085.  
  3086.                public class ShowOff implements CallShow {
  3087.                public void Show( ) { .... }
  3088.  
  3089.                public class ShowMe implements CallShow {
  3090.                public void Show( ) { .... }
  3091.  
  3092.                public class UseShow { CallShow callthis;
  3093.                UseShow( CallShow withthis ) { callthis = withthis; }
  3094.                void ReadyToShow( ) { callthis.Show( ); }
  3095.  
  3096.                // in some other class that uses all this stuff:
  3097.                UseShow use_1 = new UseShow( new ShowOff() );
  3098.                UseShow use_2 = new UseShow( new ShowMe() );
  3099.  
  3100.           and then the ReadyToShow() method on use_1 or use_2 will call the
  3101.           appropriate method, as if you had stored a pointer to the method.
  3102.      10.5 How do I execute a command from Java?
  3103.           A. Use Runtime.getRuntime.exec( myCommandString ) Where
  3104.           myCommandString is something like "/full/pathname/command"
  3105.      10.6 How do I do I/O redirection in Java using exec() ?
  3106.           A. This solution works on Unix platforms using either JDK 1.0.2,
  3107.           or JDK 1.1. The trick is to use an array of Strings for the
  3108.           command line:
  3109.  
  3110.                String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"};
  3111.  
  3112.           If you don't do this, and simply use a single string, the shell
  3113.           will see the -c and /bin/ls and ignore everything else after that.
  3114.           It only expects a single argument after the -c.
  3115.  
  3116.           import java.io.*;
  3117.           import java.util.*;
  3118.  
  3119.           class IoRedirect {
  3120.               public static void main(String Argv[]) {
  3121.                   try {
  3122.                       String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"};
  3123.                       Process p = Runtime.getRuntime().exec(command);
  3124.                       p.waitFor();
  3125.                       System.out.println("return code: "+ p.exitValue());
  3126.                   }
  3127.                   catch (IOException e) {
  3128.                      System.err.println("IO error: " + e);
  3129.                   }
  3130.                   catch (InterruptedException e1) {
  3131.                      System.err.println("Exception: " + e1.getMessage());
  3132.                   }
  3133.               }
  3134.           }
  3135.  
  3136.      10.7 So why can't I exec common DOS commands this way (as in 10.6)?
  3137.           A. The reason is that many of the DOS commands are not individual
  3138.           programs, but merely "functions" of command.com. There is no
  3139.           DIR.EXE or COPY.EXE for example. Instead, one executes the command
  3140.           processor (shell) explicitly with a request to perform the builtin
  3141.           command, like so: Runtime.getRuntime().exec("command.com /c dir")
  3142.           for example. On NT, the command interpreter is "cmd.exe", so the
  3143.           statement would be
  3144.           Runtime.getRuntime().exec("cmd /c dir")
  3145.  
  3146.           This is a Windows, Windows95 and NT-specific problem.
  3147.      10.8 OK, how do I read the input from a command?
  3148.           A. As above (10.5, 10.6), adjusted like this:
  3149.  
  3150.                BufferedReader pOut=
  3151.                      new BufferedReader(
  3152.                      new InputStreamReader(p.getInputStream()));
  3153.                try {
  3154.                    String s = pOut.readLine();
  3155.                    while (s != null) {
  3156.                        System.out.println(s);
  3157.                        s = pOut.readLine();
  3158.                    }
  3159.                } catch (IOException e) { }
  3160.  
  3161.           Another possibility is to read chunks of whatever length as they
  3162.           come in:
  3163.           ...
  3164.  
  3165.                p = r.exec(cmd);
  3166.                InputStream is = p.getInputStream();
  3167.                int len;
  3168.                byte buf[] = new byte[1000];
  3169.                try {
  3170.                    while( (len = data.read(buf)) != -1 ) {
  3171.                    String str = new String(buf,0,0,len);
  3172.                    System.out.println( "Process out: " + str );
  3173.                }
  3174.                catch( java.io.EOFException eof ) {
  3175.  
  3176.                ...
  3177.  
  3178.                }
  3179.  
  3180.                catch( java.io.IOException ioe ) {
  3181.  
  3182.                ...
  3183.  
  3184.                }
  3185.  
  3186.      10.9 How do I compile code which has a cyclic dependency, i.e class
  3187.      pkg1.X contains a reference to class pkg2.Y ?
  3188.           A. You throw both classes at the compiler at the same time.
  3189.                javac pkg1/X.java pkg2/Y.java
  3190.      10.10 How can I store the errors from the javac compiler in a DOS file?
  3191.      javac foo.java > errorfile seems not to work
  3192.           A. javac write errors to stderr, so on NT use:
  3193.                javac myfile.java 2> errors.dat
  3194.           On Win95, this doesn't work (as command.com is very poor
  3195.           software), so you have to use the javac error redirection
  3196.           mechanism:
  3197.                javac -J-Djavac.pipe.output=true myfile.java > errors.txt
  3198.      10.11 How can I pretty-print Java source?
  3199.           A. Try http://www.CS.ORST.EDU/~speton/percolator/ (currently in
  3200.           Beta)
  3201.           Or http://www.parallax.co.uk/~rolf/download/jpp.pl
  3202.           Some Unix utilities work adequately:
  3203.  
  3204.           indent (fails with "//" comments though)
  3205.           cb (very few style choices though)
  3206.  
  3207.           alias printjava 'vgrind -lC++ -t -w \!* | lp'
  3208.           works pretty well too.
  3209.      10.12 What is the point of creating the temporary reference to
  3210.      this.layoutMgr? This code is from the 1.0 AWT, and the programmer was
  3211.      probably pretty skilled.
  3212.  
  3213.           public synchronized void layout() {
  3214.                  LayoutManager layoutMgr = this.layoutMgr;
  3215.                  if (layoutMgr != null) {
  3216.                     layoutMgr.layoutContainer(this);
  3217.                  }
  3218.           }
  3219.  
  3220.           A. The code makes a local copy of a global variable for one or
  3221.           both of two reasons.
  3222.  
  3223.           The first reason is that accessing local variables can be faster
  3224.           than accessing (non final) member variables It's good for loops or
  3225.           where there are many references in the source.
  3226.  
  3227.           The second reason is so that even if other threads update the
  3228.           global,
  3229.  
  3230.                this.layoutMgr = someOtherLayoutMgr;
  3231.  
  3232.           this method will still have a pointer to the original layoutMgr.
  3233.  
  3234.           If the local variable were omitted, and another thread used the
  3235.           setLayout() method to change layoutMgr to null between when the
  3236.           layout method checked for null and when it invoked layoutMgr's
  3237.           layoutContainer method, a NullPointerException would result.
  3238.  
  3239.           Note that the synchronized keyword on the layout method doesn't
  3240.           help any, since setLayout (which could make such a dire change)
  3241.           isn't synchronized. Synchronized methods only lock out other
  3242.           synchronized methods on this object. (The unhelpful synchronized
  3243.           keyword on the layout method is gone in JDK 1.1.)
  3244.  
  3245.           There are two alternative solutions. One would be to make
  3246.           setLayout synchronized and make layoutMgr private, so that it
  3247.           can't be set other ways. This provides a stronger form of thread
  3248.           serialization, in that you would never be able to see an old
  3249.           layout manager being used after it had been replaced. However, it
  3250.           is slower. Another option that provides no increase in thread
  3251.           serialization over the original would be to catch the
  3252.           NullPointerException.
  3253.  
  3254.           Threads programming is hard! This idiom was probably put in place
  3255.           by someone who got really bitten by this in the past.
  3256.      10.13 What is the difference between "a & b" and "a && b" ?
  3257.           A. "a & b" takes two boolean operands, or two integer operands. It
  3258.           always evaluates both operands. For booleans, it ANDs both
  3259.           operands together producing a boolean result. For integer types,
  3260.           it bitwise ANDs both operands together, producing a result that is
  3261.           the promoted type of the operands (i.e. long, or int). "|" is the
  3262.           corresponding bitwise OR operation. "^" is the corresponding
  3263.           bitwise XOR operation.
  3264.  
  3265.           "a && b" is a "conditional AND" which only takes boolean operands.
  3266.           It always avoids evaluating its second operand if possible. If a
  3267.           is evaluated to false, the AND result must be "false" and the b
  3268.           operand is not evaluated. This is sometimes called
  3269.           "short-circuited" evaluation. "||" is the corresponding
  3270.           short-circuited OR operation.
  3271.  
  3272.           Possible mnemonic: The longer operators "&&" or "||" try to
  3273.           shorten themselves by not evaluating the second operator if they
  3274.           can.
  3275.      10.14 If I create a thread, and then null out the reference to it, what
  3276.      happens to the thread? Does it get interrupted or what?
  3277.           A. The code looks like this:
  3278.  
  3279.                Thread t = new Thread( my_runnable_obj );
  3280.                t.start();
  3281.                ...
  3282.                t = null; // what happens to the thread?
  3283.  
  3284.           The answer is that *you* may no longer have a reference to the
  3285.           thread, but the JVM still does. Once a thread is started, and as
  3286.           long as it keeps running, it is a root object. Root objects are
  3287.           the starting points for "things in use" that the garbage collector
  3288.           uses.
  3289.      10.15 How do I calculate the number of days between two dates?
  3290.           A. There is no API for this (there should be), but you can
  3291.           calculate it by hand, like this:
  3292.  
  3293.                Calendar earlierDate = new GregorianCalendar();
  3294.                Calendar laterDate = new GregorianCalendar();
  3295.  
  3296.                earlierDate.set(1997, 1, 1, 0, 0, 0);    // Jan 01, 1997
  3297.                laterDate.set(1998, 1, 1, 0, 0, 0);      // Jan 01, 1998
  3298.  
  3299.                // the first getTime() returns a Date, the second takes
  3300.                // that Date object and returns millesecs since 1/1/70.
  3301.                // The API has misleading and horrible naming here, sorry.
  3302.                long duration =    laterDate.getTime().getTime()
  3303.                                 - earlierDate.getTime().getTime();
  3304.  
  3305.                long nDays = duration / (24 * 60 * 60 * 1000);
  3306.                System.out.println("difference in days: " + nDays);
  3307.  
  3308.      10.16 How can a Java program determine the level of JDK support given
  3309.      by the underlying VM? I.e. is it running in a JDK 1.0.2 or 1.1 VM?
  3310.           A. Look at the java.version system property with:
  3311.  
  3312.                String ver = System.getProperty("java.version");
  3313.  
  3314.           There isn't a lot of standardization on the string contents
  3315.           however. Another possibility is to try { ... } a library method
  3316.           that didn't exist in JDK 1.0.2, and catch the exception. If you
  3317.           got an exception, it's a 1.0 implementation.
  3318.                                 ------------------
  3319.  
  3320. 11. FOR C and C++ AFFICIONADOS
  3321.  
  3322.      11.1 How do I translate C/C++ into Java or vice-versa?
  3323.           A. In general it is not simple to translate C/C++ into Java, as
  3324.           Java lacks the arbitrary pointer arithmetic of those languages. If
  3325.           your C code does not use pointer arithmetic, automatic translation
  3326.           gets a lot simpler. Try these URLs:
  3327.                http://www.ist.co.uk (search for X-Designer 4.6: Java
  3328.                edition).
  3329.                http://members.aol.com/laffra/c2j.html
  3330.                http://www.ilog.com/
  3331.                http://www.cs.wustl.edu/~schmidt/java_notes.html
  3332.           Going the other way there are currently three freely-available
  3333.           tools to translate Java into C. It seems that these have been done
  3334.           for hacking value, rather than practical purposes.
  3335.  
  3336.              + j2c from Japan,
  3337.                     http://www.webcity.co.jp/info/andoh/java/j2c.html
  3338.              + Toba from the Sumatra research project, translates 1.0.2
  3339.                .class files into .c source code
  3340.                     http://www.cs.arizona.edu/sumatra/toba
  3341.              + JCC from Nik Shaylor.
  3342.                     http://www.digiserve.com/nshaylor/jcc.html
  3343.           None of them support the AWT yet, and both j2c and JCC have
  3344.           additional restrictions.
  3345.  
  3346.           There's a product to convert Visual Basic to Java. Details at
  3347.                http://www.blackdirt.com and
  3348.                     http://www.javadelphi.com (also a Delphi-to-Java source
  3349.                     converter) and
  3350.                     http://www.tvobjects.com
  3351.                This program dumps info about the class file:
  3352.                     http://www.professionals.com/~cmcmanis/java/dump/index.html
  3353.                Chuck McManis was one of Sun's original Java whackers.
  3354.  
  3355.      11.2 How are finalizers different from C++ destructors?
  3356.           A. Java objects are not explicitly deleted and do not have
  3357.           destructors. Instead they are implicitly garbage collected when
  3358.           the JVM realises your program can no longer access them. Typically
  3359.           this technology is _not_ based on reference counting and _will_
  3360.           cope with circular references.
  3361.  
  3362.           Every object has a routine called finalize() which will be called
  3363.           before the object is collected. This is Java's nearest equivalent
  3364.           to C++'s destructor. However, it is not a good idea to rely on
  3365.           finalization for the timely freeing of resources.
  3366.  
  3367.           This is because garbage collection and hence finalization may be
  3368.           arbitrarily delayed, and may never happen at all if the program
  3369.           terminates before it runs out of memory. You should instead
  3370.           provide your objects with methods similar to Graphics.dispose() to
  3371.           free resources, and call the
  3372.           dispose() method explicitly when you have finished using them -
  3373.           typically within the "finally" clause of a "try/catch" block. You
  3374.           may then call your dispose() method from within your finalize()
  3375.           method as a last-ditch attempt to free the resource if someone
  3376.           forgets.
  3377.  
  3378.           Alas, all this means the C++ idiom of "object construction is
  3379.           resource aquisition" does not translate well to Java. However,
  3380.           note that 90% of destructors in C++ are there to free memory, and
  3381.           the GC means you don't need to do that in Java. As well as fixing
  3382.           an important source of bugs, the GC is essential to Java's
  3383.           security model; without it you could forge object references by
  3384.           preserving the reference after the object has been deleted.
  3385.  
  3386.           If your program appears to be crashing due to running out of some
  3387.           system resource (like File, Window or Graphics handles), it
  3388.           probably because the system is running out of handles before it
  3389.           has run out of memory. Check that you have called the dispose()
  3390.           method (or equivalent) on every object that uses system resources.
  3391.           You can help the GC a little bit more by explicitly
  3392.           NULLing out references that you've finished with.
  3393.      11.3 What's the Java equivalent of sizeof()?
  3394.           A: There isn't one. sizeof() in C and C++ is used in three main
  3395.           places:
  3396.                1) To check on the size of a primitive type. In Java, the
  3397.                sizes of primitive types are fixed in the language
  3398.                specification (a short is _always_ 16 bits; an int is
  3399.                _always_ 32 bits, etc), so this is no longer necessary.
  3400.  
  3401.                2) In memory allocation (i.e. malloc (32 * (sizeof(int));) In
  3402.                Java you always allocate a specific type of object, rather
  3403.                than a block of raw memory that you will fill as you like.
  3404.                The system always knows the size of the kind of objects you
  3405.                are allocating. So sizeof is not needed.
  3406.  
  3407.                3) in pointer arithmetic (i.e. p += sizeof (int)) Pointer
  3408.                arithmetic of this type is not allowed in Java, so this isn't
  3409.                necessary, either.
  3410.  
  3411.                For all these reasons, there is no need for a Java sizeof()
  3412.                operator.
  3413.      11.4 Does Java have the equivalent of "const" arguments in C and C++?
  3414.           A. Java 1.1 adds the ability to use the "final" keyword to make
  3415.           arguments constant. When used to qualify a reference type,
  3416.           however, this keyword indicates that the reference is constant,
  3417.           not that the object or array referred to is constant. For example,
  3418.           the following Java code:
  3419.  
  3420.                void foo(final MyClass c, final int a[]) {
  3421.                        c.field = 7; // allowed
  3422.                        a[0] = 7; // allowed
  3423.                        c = new MyClass(); // final means this is NOT allowed
  3424.                        a = new int[13]; // final means this is NOT allowed
  3425.                }
  3426.  
  3427.           is roughly equivalent to the following C/C++ code:
  3428.  
  3429.                void foo(MyClass * const c, int * const a) {
  3430.                        c->field = 7; // allowed
  3431.                        a[0] = 7; // allowed
  3432.                        c = new MyClass(); // const means this is NOT allowed
  3433.                        a = new int[13]; // const means this is NOT allowed
  3434.                }
  3435.  
  3436.           Java does not have any equivalent to the following C/C++ function
  3437.           declarations:
  3438.  
  3439.                void foo(const MyClass *c); // a pointer to a const class
  3440.                void foo(const int *a); // a pointer to a const int
  3441.                void foo(const int a[]); // a pointer to an array of const ints
  3442.  
  3443.      11.5 Are there any hacks around this?
  3444.           A. Certainly! There are always hacks around stuff. One way of
  3445.           enforcing constant values is to have two interfaces, a constant
  3446.           one and a non-constant one, e.g.
  3447.  
  3448.                public interface ConstFoo {
  3449.                int getValue();
  3450.                }
  3451.  
  3452.                public interface Foo extends ConstFoo {
  3453.                int getValue();
  3454.                void setValue(int i);
  3455.                }
  3456.  
  3457.           Then when you want to receive a parameter that cannot be modified
  3458.           you have:
  3459.  
  3460.                void noChange(ConstFoo foo);
  3461.  
  3462.           For a parameter that can be modified
  3463.  
  3464.                void change(Foo foo);
  3465.  
  3466.      11.6 How can I write C/C++ style assertions in Java?
  3467.           A. The two classes shown below provide an assertion facility in
  3468.           Java. Set Assert.enabled to true to enable the assertions, and to
  3469.           false to disable assertions in production code. The
  3470.           AssertionException is not meant to be caught--instead, let it
  3471.           print a trace. Since the exception is not meant to be caught, we
  3472.           just extend Error instead of RuntimeException. As with
  3473.           RuntimeException, a method does not need to declare that it throws
  3474.           Error. In addition programmers are less likely to write
  3475.           "catch(Error) ..." than "catch(RuntimeException)".
  3476.  
  3477.           With a good optimizing compiler there will be no run time overhead
  3478.           for many uses of these assertions when Assert.enabled is set to
  3479.           false. However, if the condition in the assertion may have side
  3480.           effects, the condition code cannot be optimized away. For example,
  3481.           in the assertion
  3482.  
  3483.                Assert.assert(size() <= maxSize, "Maximum size exceeded");
  3484.  
  3485.           the call to size() cannot be optimized away unless the compiler
  3486.           can see that the call has no side effects. C and C++ use the
  3487.           preprocessor to guarantee that assertions will never cause
  3488.           overhead in production code. Without a preprocessor, it seems the
  3489.           best we can do in Java is to write
  3490.  
  3491.                Assert.assert(Assert.enabled && size() <= maxSize, "Too big");
  3492.  
  3493.           In this case, when Assert.enabled is false, the method call can
  3494.           always be optimized away, even if it has side effects.
  3495.  
  3496.                public class AssertionException extends Error {
  3497.                     public AssertionException(String s) {
  3498.                        super(s);
  3499.                     }
  3500.                }
  3501.  
  3502.                public final class Assert {
  3503.                    public static final boolean enabled = true;
  3504.                    public static final void assert(boolean b, String s) {
  3505.                        if (enabled && !b)
  3506.                            throw new AssertionException(s);
  3507.                   }
  3508.                }
  3509.  
  3510.      11.7 How do I do stuff like scanf and sscanf in C/C++? And how do I do
  3511.      stuff like sprintf, e.g.
  3512.  
  3513.           float x = 12345.6789;
  3514.           printf("%6.3f/n", x);
  3515.  
  3516.           A. You can break a string like "5 loaves 2 fishes" into its parts
  3517.           by using java.util.StringTokenizer. This is the Java equivalent of
  3518.           sscanf().
  3519.  
  3520.           StreamTokenizer does a similar thing on a file or any stream (i.e,
  3521.           what scanf() and fscanf() do in C).
  3522.  
  3523.           To do formatted character output, create a format string, and then
  3524.           use that to format your binary value, e.g.
  3525.  
  3526.                import java.text.*;
  3527.  
  3528.                float fi = 1234.56789F;
  3529.                DecimalFormat df2 = new DecimalFormat( "0.000" );
  3530.                System.out.println( df2.format(fi) );
  3531.  
  3532.           gives:
  3533.  
  3534.                1234.567
  3535.           There are lots of different characters you can feed to the
  3536.           DecimalFormat constructor, not just "0". See
  3537.           $JAVAHOME/src/java/DecimalFormat.java source for details.
  3538.  
  3539.      11.8  What is the Java equivalent of C++ friend"?
  3540.           A: The keyword "friend" in C++ is a hack to allow a piece of code
  3541.           to access the private member declarations of another class. In
  3542.           Java, you would do this by labelling, not the friend, but the
  3543.           private members. Instead of making them private, make them
  3544.           protected. Classes in the same package have automatic "friendship"
  3545.           in that they can access each other's protected fields.
  3546.  
  3547.      11.9 Does anything like the C++ Standard Template Library exist for
  3548.      Java ?
  3549.           A: Yes, only it's better and simpler to use in Java. It's called
  3550.           the Java Generic Library. This library (JGL) is freely
  3551.           downloadable from http://www.objectspace.com/
  3552.  
  3553.           It includes about a dozen nice data structures (including sets and
  3554.           bags) and algorithms like unions, searching, and sorting.
  3555.  
  3556.           [Some Java vendors are bundling it with their next release]
  3557.  
  3558.                              -------------------
  3559.  
  3560. 12. FURTHER RESOURCES
  3561.  
  3562.      12.1 Useful URLS
  3563.           Site with the latest copy of this FAQ: http://www.best.com/~pvdl/
  3564.  
  3565.           Other Java resources:
  3566.           The Java "Hall" of Fame: http://www.apl.jhu.edu/~hall/java/
  3567.           good glossary: http://oberon.ark.com/~roedy
  3568.           conversions: http://oberon.ark.com/~roedy/convert.html
  3569.           good JDBC FAQ: http://www.yoyoweb.com/Javanese/JDBC/FAQ.html
  3570.           general Java: http://java.miningco.com/
  3571.  
  3572.           Tutorial:
  3573.           http://java.sun.com:80/nav/read/Tutorial/index.html
  3574.           http://www.phrantic.com/scoop/onjava.html
  3575.  
  3576.           Java Book lists:
  3577.           http://lightyear.ncsa.uiuc.edu/~srp/java/reviews.html
  3578.           http://www.netcharts.com/majug/reviews.html
  3579.           http://www.avena.net/~dong/book.htm
  3580.           http://wwwiz.com/books
  3581.  
  3582.           Javasoft site: http://java.sun.com
  3583.  
  3584.           General sharing and exchange of Java info:
  3585.           http://www.gamelan.com
  3586.           http://www.JavaShareware.com
  3587.      12.2 Newsgroups
  3588.           These are the Java newsgroups since the reorganization that I
  3589.           arranged in April 1997
  3590.  
  3591.           comp.lang.java.help simple programming and setup questions
  3592.           comp.lang.java.announce (moderated) announcements
  3593.           comp.lang.java.advocacy for arguments: no it isn't, yes it is
  3594.           comp.lang.java.programmer programming in Java
  3595.           comp.lang.java.security security issues
  3596.           comp.lang.java.machine JVM and native interfaces
  3597.           comp.lang.java.databases JDBC,ODBC, java access to DBs.
  3598.           comp.lang.java.softwaretools IDES, editors, compilers, tools, etc
  3599.           comp.lang.java.gui AWT, IFC, JFC, AFC, Vibe, etc etc
  3600.           comp.lang.java.beans Software components in Java
  3601.  
  3602.           Please make an effort to post only to the single most appropriate
  3603.           group.
  3604.  
  3605.           As with the other language groups on Usenet (comp.lang.c,
  3606.           comp.lang.c++, etc) questions about products from specific vendors
  3607.           that only work on one specific platform are best posted to other
  3608.           newsgroups. For example, questions about ActiveX belong in
  3609.           comp.os.ms-windows.programmer.ole, not the Java groups. For
  3610.           questions about J/Direct try the group
  3611.           microsoft.public.java.visualj++ or microsoft.public.java.sdk.
  3612.           These are available from Microsoft's news server
  3613.           msnews.microsoft.com .
  3614.      12.3 Are there any Java libraries for sorting, etc?
  3615.           A. A sort class has not yet been made part of the standard
  3616.           library. It should be. If you have the demos that come with the
  3617.           JDK, take a look at the class SortDemo. Alternatively, use one of
  3618.           the several classic sorts available from Roedy Green. They are
  3619.           supplied free with heavily commented Java source code.
  3620.  
  3621.           See "QuickSort", "HeapSort" and "RadixSort" in the Java glossary
  3622.           at http://oberon.ark.com/~roedy/index.html .
  3623.  
  3624.           Also, try the Java Generic Library. This library (JGL) is freely
  3625.           downloadable from http://www.objectspace.com/
  3626.  
  3627.           Also Visual Engineering has JChart at: http://www.ve.com. No
  3628.           licensing fees.
  3629.      12.4 Why doesn't somebody write a shell in Java? Then they could use it
  3630.      on all platforms!
  3631.           A. Somebody has done just that. Look at http://www.jsh.net/
  3632.      12.5 Are there any URLs for other libraries?
  3633.           A. Indeed, there are. The Java3D Repository
  3634.           http://java3d.sdsc.edu/
  3635.      12.6 Are there any URLs for regular expression handlers in Java?
  3636.           A. http://www.oroinc.com/products/OROMatcher.html This comes from
  3637.           ORO Inc, is free, and handles Perl5 style exprs.
  3638.  
  3639.                                    -----------------
  3640.  
  3641.           Acknowledgements:
  3642.           Original FAQ copyright February 1997 Peter van der Linden
  3643.  
  3644.           Contributions from:
  3645.  
  3646.           Matt Kennel, Patric Jonsson, Brad Van Tighem, Tony Hursh , Glenn L
  3647.           Vanderburg, Peter Jones, John McDowall, Jim Driscoll, Uday, Dave
  3648.           Harris, Bill Wilkinson, Tom Valesky, Dan Drake, Giles Thomas,
  3649.           Mitch Baltuch, Guy Ruth Hammond, Gordon Keith, Jason Brome, Shani
  3650.           Kerr, Steve Chapel, Timothy Wolters, Robert Lynch, Jake Cormier,
  3651.           Sean C Sullivan, Joseph A. Millar, Jim Frost, Jim Balter, Jeff
  3652.           Bauer, John Kochmar, Carl Burke, William Stubbs, Mark Smith,
  3653.           Volker Turau, Real Gagnon, Russell Gold, Max Hailperin, Bill
  3654.           Tschumy, Marco Nijdam, Marc Pawlowsky, Laurence Vanhelsuwe,Ian
  3655.           Macgregor, Mike Faulkner, Rich Koch, Will Clark, Govind Seshadri,
  3656.           Rich Simkin, Ian Stiles, Kieren, Darren Christie, Tom Lane,
  3657.           Michael Jungmann, Rob Mayoff, George Ruban, Tom McCann, David
  3658.           Hopwood, Thomas Phan, Kai Stuke, Rolf Howarth, Derek Snider, David
  3659.           Boydston, Andy Godwin, John F. Dumas, Doug Bell, David J. Biesack,
  3660.           Tiger Quimpo, Martin Hugh Rogers, Brian Krahmer, Ian Burrell,
  3661.           Nikki Locke, Bin Li, Jackson Thompson, Steve Odendahl, Greg Smith,
  3662.           Jeffrey C. Ollie, Mark Halvin, Jeremy Cook, Lak Ming Lam, Peter S.
  3663.           Morris, Mark Halvin, Juergen Keil, Alex Stewart, Mike Abney,
  3664.           Rodney Stephenson
  3665.  
  3666.           [<your name here>: send in a suggested FAQ *with the answer*]
  3667.  
  3668.           ----
  3669.  
  3670.           I am maintaining a FAQ list to address specifically programming
  3671.           issues
  3672.           (not a general tutorial on Java). Please feel free to mail me
  3673.           entries for it.
  3674.           Question with answer gets you a credit in the FAQ.
  3675.           I can be emailed at: pvdl@best.com
  3676.           Sun Certified Java Programmer.
  3677.  
  3678.           -- end --
  3679.  
  3680.  
  3681.  
  3682.  
  3683.  
  3684.  
  3685. -- 
  3686. Peter van der Linden,                     Java Programmer's FAQ
  3687. Certified Java Programmer.                --->    http://www.best.com/~pvdl
  3688.